朋友(并查集的查找合并)

在社交的过程中,通过朋友,也能认识新的朋友。在某个朋友关系图中,
假定 A 和 B 是朋友,B 和 C 是朋友,那么 A 和 C 也会成为朋友。
即,我们规定朋友的朋友也是朋友。
现在,已知若干对朋友关系,询问某两个人是不是朋友。
请编写一个程序来解决这个问题吧。
输入格式
第一行:三个整数 n,m,p(n≤5000,m≤5000,p≤5000)分别表示有n 个人,m
 个朋友关系,询问p 对朋友关系。
接下来 m 行:每行两个数
Ai,Bi1≤Ai,Bi≤N,表示Ai​
 和 Bi具有朋友关系。
接下来 p 行:每行两个数,询问两人是否为朋友。
输出格式
输出共 p 行,每行一个Yes或No。表示第
iii 个询问的答案为是否朋友。

样例输入:

6 5 3
1 2
1 5
3 4
5 2
1 3
1 4
2 3
5 6

样例输出:

Yes
Yes
No
#include<iostream>
using namespace std;

const int MAX = 10000;
int father[MAX];

int find(int temp)
{
	if(father[temp]== temp)
	{
		return temp;
	}
	else
	{
		return find(father[temp]);	
	}
}
void merge(int x,int y)// x 连到 y 后面 
{
	int a,b;
	a = find(x);
	b = find(y);
	//cout<<x<<" 的老大是 "<<a<<endl;
//	cout<<y<<" 的老大是 "<<b<<endl; 
	if(a != b )
	{
		father[a] = b;
	}
	//cout<<x<<"和"<<y<<" 的老大是 "<<b<<endl;
}
int main()
{
	int n,m,p,i,temp_1,temp_2;
	
	cin>>n>>m>>p;
	for(i=0;i<n;++i)
	{
		father[i] = i;
	}
	for(i=0;i<m;++i)
	{
		cin>>temp_1>>temp_2;
		merge(temp_1,temp_2);	
	}
	for(i=0;i<p;++i)
	{
		cin>>temp_1>>temp_2;
		if(find(temp_1)==find(temp_2))
		{
			cout<<"Yes"<<endl;
		}
		else
		{
			cout<<"No"<<endl;
		}
	}
	return 0;
}

在写的时候出现了  “  error :reference to ' max' is ambiguous  ”   , 原因是我用来开father的max与库中的重名了,改成MAX就没关系了

猜你喜欢

转载自blog.csdn.net/qq_42580577/article/details/87829406
今日推荐