首页 > 代码库 > HDOJ-1232 畅通工程【并查集裸题】

HDOJ-1232 畅通工程【并查集裸题】

题目传送门 : http://acm.hdu.edu.cn/showproblem.php?pid=1232

 

并查集的裸题

 

AC code:

#include <iostream>
#define MAXN 1050
using namespace std;
int pre[MAXN];
int Find(int pos) {
    int r = pos;
    while (r != pre[r])
        r = pre[r];

    int i = pos;
    while (i != r) {
        int t = pre[i];
        pre[i] = r;
        i = t;
    }
    return r;
}
void Join(int posX, int posY) {
    int rootX = Find(posX), rootY = Find(posY);
    if (rootX != rootY)
        pre[rootX] = rootY;
}
int main()
{
    int N, M;
    while (cin >> N >> M && N) {
        int ct = 0;
        for (int i = 1; i <= N; ++i)
            pre[i] = i;
        int cityA, cityB;
        while (M--) {
            cin >> cityA >> cityB;
            Join(cityA, cityB);
        }
        for (int i = 1; i <= N; ++i)
            if (pre[i] == i)
                ct++;
        cout << ct - 1 << endl;
    }
    return 0;
}

 

HDOJ-1232 畅通工程【并查集裸题】