题目描述
给定一个无向图和其中的所有边,判断这个图是否所有顶点都是连通的。
输入
每组数据的第一行是两个整数 n 和 m(0<=n<=1000)。n 表示图的顶点数目,m 表示图中边的数目。如果 n 为 0 表示输入结束。随后有 m 行数据,每行有两个值 x 和 y(0
输出
对于每组输入数据,如果所有顶点都是连通的,输出”YES”,否则输出”NO”。
样例输入
4 3
1 2
2 3
3 2
3 2
1 2
2 3
0 0
样例输出
NO
YES
来源
2011年吉林大学计算机研究生机试真题
思路:使用并查集来判断是否连通,即是否都有同一个父节点
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
int uset[1050];
int find(int x){
if(x!=uset[x])
uset[x] = find(uset[x]);
return uset[x];
}
int main()
{
int n, m;
int a, b;
while(scanf("%d %d", &n, &m)!=EOF && n){
for(int i = 0; i <= n; i++){
uset[i] = i;
}
for(int i = 0; i < m; i++){
scanf("%d %d", &a, &b);
a = find(a);
b = find(b);
if(a!=b)
uset[a] = b;
}
int flag = 1, u = find(1);
for(int i = 2; i <= n; i++){
if(u!=find(i)){
flag = 0;
break;
}
}
if(flag == 1)
cout << "YES" << endl;
else
cout << "NO" << endl;
}
return 0;
}