hdu1232 畅通工程

#include <iostream> 
#include <fstream>
using namespace std;
#ifndef ONLINE_JUDGE
ifstream fin("test.txt");
#define cin fin
#endif
int bin[1010];
int findx(int x)
{
    int r = x;
    while(bin[r] != r)
    {
        r = bin[r];
    }
    return r;
}
void merge(int x,int y)
{
    bin[x] = y;
}
int main()
{
    int n,m,a,b,i,count;
    while(cin >> n >> m)
    {
        for(i = 1 ; i <= n ; ++i)
        bin[i] = i;
        count = -1;
        while(m--)
        {
            cin >> a >> b;
            int fx = findx(a),fy = findx(b);
            if(fx != fy)
            merge(fx,fy);
        }
        for(i = 1; i<= n ; ++i)
        if(bin[i] == i)
        count++;
        cout << count << endl;
    }
    return 0;
}

 

posted @ 2013-02-04 21:22  see_why  阅读(179)  评论(0)    收藏  举报