Description

如果无向图G每对顶点v和w都有从v到w的路径,那么称无向图G是连通的。现在给定一张无向图,判断它是否是连通的。

Input

第一行有2个整数n和m(0 < n,m < 1000000), 接下来m行每行有2个整数u,v (1<=u,v<=n)表示u和v有边连接。

Output

如果无向图是连通的输出yes,否则输出no

Sample Input
4 6
1 2
2 3
1 3
4 1
2 4
4 3

Sample Output
yes

[图的遍历算法]


题目分析:判断图是否连通,可用dfs和bfs遍历图算法,注意点数目较多,又是稀疏图的话,最后使用邻接表的方法存储。另外推荐采用的是并查集的方法。初始化时将每个节点看作一个集合,则每给出一条边即把两个集合合并。最后遍历所有点,有几个集合便有几个连通分量,若只有一个集合说明图连通。并查集方法通常情况下时间效率较高,还能判断一个图是否有回路,在kruskal算法中也可以使用。

下分别给出三种方法的代码。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;

int set[1000005];

int find(int x){

   returnx==set[x]?x:(set[x]=find(set[x]));   //递归查找集合的代表元素,含路径压缩。

}

int main()

{

   int n,m,i,x,y;

   scanf("%d%d",&n,&m);

   for(i=1;i<1000005;++i)        //初始化个集合,数组值等于小标的点为根节点。

       set[i]=i;

   for(i=0;i<m;++i){

       int a,b;

       scanf("%d%d",&a,&b);

       int fx=find(a),fy=find(b);

       set[fx]=fy;                      //合并有边相连的各个连通分量

   }

   int cnt=0;

   for(i=1;i<=n;++i)          //统计集合个数,即为连通分量个数,为一时,图联通。

       if(set[i]==i)

           ++cnt;

   if(cnt==1)
       printf("yes\n");
   else printf("no\n");

   return 0;
}
并查集

相关文章: