#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;
const int MAX = 10005;
int pre[MAX];
int Find(int x){
return (pre[x] == x) ? x : Find(pre[x]);
}
void init()
{
for(int i=0; i<MAX; i++)
pre[i]=i;
return;
}
int main ()
{
init();
int n, m;
cin >> n >> m;
int com, x, y;
while(m--){
cin >> com >> x >> y;
x = Find(x);
y = Find(y);
if(com == 0)
pre[x] = y;//合并
else if(x == y)
cout << 1 << endl;
else cout << 0 << endl;
}
return 0;
}
本文介绍了一种使用C++实现的并查集数据结构,详细展示了如何初始化并查集,查找元素所属集合,以及如何进行集合的合并操作。通过一个具体的程序实例,讲解了并查集在解决集合间关系问题上的应用。
465

被折叠的 条评论
为什么被折叠?



