判断图的连通性

并查集写法:

#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;
}
原文地址:https://www.cnblogs.com/kls123/p/8534655.html