首页 > 代码库 > find 并查集

find 并查集

// find  并查集 #include<cstdio>#include<cstring>#include<cstdlib>#include<iostream>#include<algorithm>#include<cmath>#include<queue>using namespace std;const int MAXN = 10000+10;int f[MAXN]; int find(int x){    if(f[x]==x)return f[x];    return f[x] = find (f[x]);}int main(){    int m,n;    scanf("%d%d",&m,&n);    for(int i=1;i<=m;i++) f[i] = i;     for(int i=1;i<=n;i++)    {        int x,y;        scanf("%d%d",&x,&y);        x=find (x);        y=find (y);        if(x!=y)        {            f[x]=y;        }    }    int ans=0;    for(int i=1;i<=m;i++)    {        if(f[i]==i) ans++;    }    cout<<ans<<endl;    return 0;}

 

find 并查集