首页 > 代码库 > hdu 1232 畅通工程

hdu 1232 畅通工程

又是一道简单并查集

#include<map>
#include<set>
#include<queue>
#include<cmath>
#include<vector>
#include<cstdio>
#include<string>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<algorithm>
#define  inf 0x0f0f0f0f

using namespace std;

const double pi=acos(-1.0);
const double eps=1e-8;
typedef pair<int,int>pii;

const int maxn=1001;
int p[maxn];
bool vis[maxn];

int find(int x)
{
    return x==p[x]?x:p[x]=find(p[x]);
}


int main()
{
    //freopen("in.txt","r",stdin);

    int n,m,x,y;
    while (scanf("%d",&n)!=EOF && n)
    {
        scanf("%d",&m);
        for (int i=0;i<=n;i++) p[i]=i;
        while (m--)
        {
            scanf("%d%d",&x,&y);
            x=find(x);
            y=find(y);
            p[x]=y;
        }
        memset(vis,0,sizeof(vis));
        int ans=0;
        for (int i=1;i<=n;i++) p[i]=find(i);
        for (int i=1;i<=n;i++)
        if (!vis[p[i]])
        {
            ans++;
            vis[p[i]]=true;
        }
        printf("%d\n",ans-1);
    }
    //fclose(stdin);
    return 0;
}