The Preliminary Contest for ICPC Asia Xuzhou 2019 B. so easy (unordered_map+并查集)

这题单用map过不了,太慢了,所以改用unordered_map,对于前面删除的点,把它的父亲改成,后面一位数的父亲,初始化的时候,map里是零,说明它的父亲就是它本身,最后输出答案的时候,输出每一位数的父亲就好了。
下面的程序可能在windows本地编译过不了,头文件放在下面。

#include <bits/stdc++.h>
using namespace std;

unordered_map<int,int>mp;

int find(int x)
{
    if (mp[x]==0) {
        return x;
    }
    return mp[x]=find(mp[x]);
}

int main()
{
    int n,q,op,num;
    scanf("%d%d",&n,&q);
    for (int i=0;i<q;i++) {
        scanf("%d%d",&op,&num);
        if (op==1) {
            mp[num]=find(num+1);
        }
        else {
            printf("%d
",find(num));
        }
    }
    return 0;
}
/*
10 10
1 5 
1 6 
1 8 
1 9
1 7
2 5
*/
#if(__cplusplus == 201103L)
#include <unordered_map>
#include <unordered_set>
#else
#include <tr1/unordered_map>
#include <tr1/unordered_set>
namespace std
{
    using std::tr1::unordered_map;
    using std::tr1::unordered_set;
}
#endif
using namespace std;

unordered_map<int,int>mp;
原文地址:https://www.cnblogs.com/xyqxyq/p/12328866.html