跳到正文

算法·理论

找爹(并查集)

CorvusCorax约 1 分钟
原文
文章信息与版本

文章信息

发布
2025年6月1日
收录
2026年2月23日
更新
2026年11月16日
篇幅
约 1 分钟

版本

  1. v2当前
  2. v1

原始爹

C++
#include <iostream>
using namespace std;
int g[200005], n, m;
int find(int x)//找根节点 
{
	if (g[x]!=x)
	{
		g[x] = find(g[x]);//爸爸的爸爸叫什么 
	}
	return g[x];
}
int main()
{
	cin>>n>>m;
	for (int i = 1;i<=n;i++)//我是我的爹 
	{
		g[i] = i;
		
	 } 
	for (int i = 1;i<=m;i++)//我是谁的爹?
	{
		int z, x, y;
		cin>>z>>x>>y;
		int fx = find(x), fy = find(y); 
		if (z==1)
		{
			g[fx] = fy;		
		}
		else
		{
			if (fx==fy) cout<<"Y\n";
			else cout<<"N\n";
		}
	}
	return 0;
}
原文