并查集详细讲解(数据结构篇)

并查集,顾名思义,就是将集合合并极其查询,为了便于讲解,我先将完整代码贴至下方,不理解的可以先看看,下方会有详细讲解。

```cpp
#include<bits/stdc++.h>
using namespace std;
int group[100001],N,M;
int get_father(int x)
{
	return (group[x]==x)?x:get_father(group[x]);
}
int main()
{
	int selected;
	cin>>N>>M;
	for(int i=1;i<N;i++)
	{
		group[i]=i;
	}
	for(int i=1;i<=M;i++)
	{
		cin>>selected;
		if(selected==1)
		{
			int X,Y;
			cin>>X>>Y;
			group[get_father(X)]=get_father(Y);
		}
		if(selected==2)
		{
			int X,Y;
			cin>>X>>Y;
			if(get_father(group[X])==get_father(group[Y]))
			{
				cout<<"Y"<<endl;
			}
			else
			{
				cout<<"N"<<endl;
			}
		}
	}
	return 0;
}

```

猜你喜欢

转载自www.cnblogs.com/zwhwebsite/p/10439356.html
今日推荐