CF1620E题解

· · 题解

题面简述

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

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

思路

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

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

考虑每次 2 操作的效果。

将所有以前插入的 x 变成 y。

我们可以考虑从后往前扫一遍,定义一个 f 数组表示到目前为止 x 实际上表示的数。遇到操作 1 直接将 f_x 塞入数组。遇到操作 2 我们将 f_x 改成 f_y 即可。(注意改成 f_y 而不是 y!)

最后逆序输出数组即可。

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

代码

#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. ...
*/