HDU 1863 畅通工程 (并查集)

原题链接:畅通工程

题目分析:典型的并查集模版题,这里就不详细叙述了。对算法本身不太了解的可以参考这篇文章:并查集算法详解


代码如下:

#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;

const int MAX = 1000;
int father[MAX];

int getfather(int v) {
    if (father[v] == v)
        return v;
    else
    {
        father[v] = getfather(father[v]); //路径压缩
        return father[v];
    }
}

void Union(int x,int y) {
    int fx = getfather(x);
    int fy = getfather(y);
    if(fy != fx)
        father[fx] = fy;
}

void init(int n) {
	for (int i = 0; i < n; i++) 
		father[i] = i;
}

int main() {
	int n, m, a, b;
	while (cin >> n >> m && n) {
		memset(father, 0, sizeof(father));
		
		init(n);
		
		for(int i = 0; i < m; i++) {
			cin >> a >> b;	
			Union(a, b);
		}
		
		int ans = 0;
		for(int i = 0; i < n; i++)
			if(father[i] == i)	
				ans++;
				
		cout << ans - 1 << endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/laugh12321/article/details/81707348