題目描述
給定一個無向圖和其中的所有邊,判斷這個圖是否所有頂點都是連通的。
輸入
每組數據的第一行是兩個整數 n 和 m(0<=n<=1000)。n 表示圖的頂點數目,m 表示圖中邊的數目。如果 n 為 0 表示輸入結束。隨后有 m 行數據,每行有兩個值 x 和 y(0<x, y <=n),表示頂點 x 和 y 相連,頂點的編號從 1 開始計算。輸入不保證這些邊是否重復。
輸出
對于每組輸入數據,如果所有頂點都是連通的,輸出"YES",否則輸出"NO"。
樣例輸
4 3
4 3
1 2
1 3
5 7
3 5
2 3
1 3
3 2
2 5
3 4
4 1
7 3
6 2
3 1
5 6
0 0
樣例輸出
YES
YES
NO
?分析:和問題A差不多的思路,用并查集檢查是否只有一個集合。當然也可以用BFS或者DFS檢查是否只有一個連通分量。
#include<algorithm>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>
#include <cstdio>
#include <queue>
#include <stack>
#include <ctime>
#include <cmath>
#include <map>
#include <set>
#define INF 0xffffffff
#define db1(x) cout<<#x<<"="<<(x)<<endl
#define db2(x,y) cout<<#x<<"="<<(x)<<", "<<#y<<"="<<(y)<<endl
#define db3(x,y,z) cout<<#x<<"="<<(x)<<", "<<#y<<"="<<(y)<<", "<<#z<<"="<<(z)<<endl
#define db4(x,y,z,r) cout<<#x<<"="<<(x)<<", "<<#y<<"="<<(y)<<", "<<#z<<"="<<(z)<<", "<<#r<<"="<<(r)<<endl
#define db5(x,y,z,r,w) cout<<#x<<"="<<(x)<<", "<<#y<<"="<<(y)<<", "<<#z<<"="<<(z)<<", "<<#r<<"="<<(r)<<", "<<#w<<"="<<(w)<<endl
using namespace std;int findFather(int father[],int x)
{if(father[x]==-1)return -1;int a=x;while(father[x]!=x){x=father[x];}while(a!=father[a]){int z=a;a=father[a],father[z]=x;}return x;
}void Union(int a,int b,int father[])
{int fa=findFather(father,a),fb=findFather(father,b);if(fa!=fb)father[fa]=father[fb];return;
}int father[1000010];
bool isroot[1000010];int main(void)
{#ifdef testfreopen("in.txt","r",stdin);
// freopen("out.txt","w",stdout);clock_t start=clock();#endif //testint n,m;while(scanf("%d%d",&n,&m),n){int father[1010],isroot[1010]={0};for(int i=1;i<=n;++i)father[i]=i;int a,b;for(int i=0;i<m;++i){scanf("%d%d",&a,&b);if(findFather(father,a)==-1)father[a]=a;if(findFather(father,b)==-1)father[b]=b;Union(a,b,father);}for(int i=1;i<=n;++i){if(father[i]==i)isroot[i]=1;}int ans=0;for(int i=0;i<1010;++i)if(isroot[i])ans++;if(ans==1)printf("YES\n");else printf("NO\n");}#ifdef testclockid_t end=clock();double endtime=(double)(end-start)/CLOCKS_PER_SEC;printf("\n\n\n\n\n");cout<<"Total time:"<<endtime<<"s"<<endl; //s為單位cout<<"Total time:"<<endtime*1000<<"ms"<<endl; //ms為單位#endif //testreturn 0;
}