判断图的连通性

并查集写法:

#include<bits/stdc++.h>
using namespace std;
const int M = 2e5+10;
int f[M];

int find(int x){
    if(x==f[x])return x;
    return f[x]=find(f[x]);
}


void mix(int x,int y){
    int fx = find(x);
    int fy = find(y);
    if(fx != fy)
       f[fx] = fy;
}

int main()
{
    int n,m,x,y;
    cin>>n>>m;
    for(int i = 1;i <= n;i ++)
        f[i] = i;
    for(int i = 0;i < m;i ++){
        cin>>x>>y;
        mix(x,y);
    }
    int ans = 0;
    for(int i = 1;i <= n;i ++){
        if(i == f[i])
            ans++;
    }
    if(ans==1)
        cout<<"yes"<<endl;
    else
        cout<<"no"<<endl;
    return 0;
}

 

posted @ 2018-03-09 16:32  冥想选手  阅读(268)  评论(0编辑  收藏  举报