题意很好理解。既然求一个节点的连通块,那么就使用并查集。
现在我们要解决的就是应怎么储存一个连通块的且排好序的点。
考虑STL中的set,当使用并查集合并时,我们将其中一个连通块的所有点全部转移到另一个连通块中,但最坏情况是O(n)的复杂度。
怎么优化呢?可以将小的连通块的点移到大的连通块中,这样可以将操作一的复杂度优化一倍。
但是这还不够,只能过2/3的数据,还能怎么优化呢?
我们发现每个块的不同点只需要存在一次就行,如果存在多个,insert()的话,首先count()会记录点的数量,之后的clear()操作依然会导致超时。
这就不得不使用另一个插入函数了:emplace()。如果要插入的数已经存在,那么就不再插入,这是O(1)的复杂度,比insert()要快不少。
其次是排序:声明set是可以为<int,greater<int>>,这样就解决了排序。
操作二直接暴力即可,k<=10
/*I lv ya*/
#include <cstdio>
#include <cstring>
#include <string>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <vector>
#include <stack>
#include <sstream>
#include <map>
#include <set>
#include <queue>
#include <stdlib.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> PII;
const int N = 2e5+5;
int n,q,fa[N];
int op;
set <int,greater<int> > s[N];
int _find(int x)///并查集操作
{
if(x==fa[x])
{
return x;
}
return fa[x]=_find(fa[x]);
}
void _union(int x,int y)
{
int xx=_find(x);
int yy=_find(y);
if(xx==yy)
{
return ;
}
int maxp,minp;
if((int)s[xx].size()>=(int)s[yy].size())///优化一
{
maxp=xx;
minp=yy;
}
else
{
maxp=yy;
minp=xx;
}
fa[minp]=maxp;
for(auto it:s[minp])
{
s[maxp].emplace(it);///emplace()优化二
}
s[minp].clear();
}
void solve()
{
cin>>n>>q;
for(int i=1;i<=n;i++)
{
fa[i]=i;
s[i].insert(i);
}
while(q--)
{
int x,y;
cin>>op>>x>>y;
if(op==1)
{
_union(x,y);
}
else
{
int pos=_find(x);
if((int)s[pos].size()<y)
{
cout<<-1<<endl;///无效情况
continue;
}
for(auto it:s[pos])///暴力枚举
{
if(y==1)
{
cout<<it<<endl;
break;
}
y--;
}
}
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(NULL),cout.tie(NULL);
int _=1;
while(_--)
{
solve();
}
return 0;
}