跳到正文

题解

CF1620E题解

sszcdjr约 3 分钟
原文
文章信息与版本

文章信息

发布
2021年12月22日
收录
2026年11月19日
更新
2026年11月19日
篇幅
约 3 分钟
获赞
14
题目
CF1620E

版本

  1. v1当前

题面简述

给出 qq 个操作,操作分为两种:

  • 1 x 在序列末尾插入数字 xx。
  • 2 x y 把序列中的所有 xx 替换为 yy。

求这个序列操作后的结果。

思路

发现这题一个重要的性质:离线询问。

即它不要你每次操作完了就提问,而是最后一次提问。

考虑每次 22 操作的效果。

将所有以前插入的 xx 变成 yy。

我们可以考虑从后往前扫一遍,定义一个 ff 数组表示到目前为止 xx 实际上表示的数。遇到操作 11 直接将 fxf_x 塞入数组。遇到操作 22 我们将 fxf_x 改成 fyf_y 即可。(注意改成 fyf_y 而不是 yy!)

最后逆序输出数组即可。

时间空间复杂度 O(q)O(q)。

代码

C++
#include <bits/stdc++.h>
#define int long long
using namespace std;
int bel[500005];
int a[500005];
int opt[500005],x[500005],y[500005];
signed main(){
	//freopen("","r",stdin);
	//freopen("","w",stdout);
	int q;
	cin>>q;
	for(int i=1;i<=500000;i++){
		bel[i]=i;
	}
	for(int i=1;i<=q;i++){
		cin>>opt[i];
		if(opt[i]==1){
			cin>>x[i];
		}
		else{
			cin>>x[i]>>y[i];
		}
	}
	int k=0;
	for(int i=q;i>=1;i--){
		if(opt[i]==1){
			k++;
			a[k]=bel[x[i]];
		}
		else{
			bel[x[i]]=bel[y[i]];
		}
	}
	for(int i=k;i>=1;i--){
		cout<<a[i]<<" ";
	}
	return 0;
}
/* things to check
1.  int overflow or long long memory need
2.  recursion/array/binary search/dp/loop bounds
3.  precision
4.  special cases(n=1,bounds)
5.  delete debug statements
6.  initialize(especially multi-tests)
7.  = or == , n or m ,++ or -- , i or j , > or >= , < or <= , - or =
8.  keep it simple and stupid
9.  do not delete, use // instead
10. operator priority
11. is there anything extra to output?
12. if you don't know where the bug is , try to clear some parts of the code
 and check each part seperately.
13. ...
*/
原文
存档评论2 条抓取于