题目描述
给定一个无向图和其中的所有边,判断这个图是否所有顶点都是连通的。
输入描述:
每组数据的第一行是两个整数 n 和 m(0<=n<=1000)。n 表示图的顶点数目,m 表示图中边的数目。随后有 m 行数据,每行有两个值 x 和 y(0<x, y <=n),表示顶点 x 和 y 相连,顶点的编号从 1 开始计算。输入不保证这些边是否重复。
输出描述:
对于每组输入数据,如果所有顶点都是连通的,输出"YES",否则输出"NO"。
示例1
输入
4 3
1 2
2 3
3 2
3 2
1 2
2 3
0 0
输出
NO
YES
题目解析:连通图,从一个结点出发可以到达任意一个节点,存在一棵生成树。与畅通工程相似,可以利用并查集建立一个生成树。生成树边数 = n-1。
代码:
#include<stdio.h>
#include<math.h>
#include<algorithm>
#include<string.h>
#include<iostream>
#include<iomanip>
#include<vector>
#include<map>
#include<set>
#include<stack>
#include<queue>
using namespace std;
const int N = 1000;
const int M = 100000000;
int Tree[N];
typedef struct{
int start;
int end;
}Edge;
Edge edge[M];
int findroot(int x){
if(Tree[x] == x){
return x;
}else{
return findroot(Tree[x]);
}
}
//和联通工程什么的都很类似,可以去看看。
//首先了解,可以将图转化为树,保证各个点连通。当连通的时候,所有的点都可以到达唯一的一个根节点
int main()
{
int n,m;
while(cin >> n >> m){
for(int i = 1; i <= n; i++){
Tree[i] = i;
}
for(int i = 0; i < m; i++){
cin >> edge[i].start >> edge[i].end;
int a = findroot(edge[i].start);
int b = findroot(edge[i].end);
if(a != b){
Tree[b] = a;
}
}
int count = 0;
for(int i = 1; i <= n; i++){
if(Tree[i] == i){ //计算有几个根节点,如果只有一个,说明是连通的
count++;
}
}
if(count == 1){
cout << "YES" << endl;
}else{
cout << "NO" << endl;
}
}
return 0;
}
3万+

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



