《算法笔记》10.3小节——图算法专题->图的遍历 问题 B: 连通图
题目描述
给定一个无向图和其中的所有边,判断这个图是否所有顶点都是连通的。
输入
每组数据的第一行是两个整数 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 test
    freopen("in.txt","r",stdin);
//    freopen("out.txt","w",stdout);
    clock_t start=clock();
    #endif //test
    int 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 test
    clockid_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 //test
    return 0;
}