跳到正文

个人记录

总结10

fangjiayuan约 1 分钟
原文

这是 2025年12月3日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2025年11月30日
收录
2025年12月12日
更新
2026年11月18日
篇幅
约 1 分钟

版本

  1. v2当前
  2. v1

村村通

C++
#include<bits/stdc++.h>

using namespace std;

int n, m, a[1005], x, y;

int find(int x){
	if(a[x] == x){
		return a[x];
	}
	return a[x] = find(a[x]);
}

void h(int x, int y){
	int a1 = find(x), a2 = find(y);
	if(a1 != a2){
		a[a2] = a1;
	}
}

int main(){
	while(1){
		int ans = 0;
		cin >> n;
		if(n == 0){
			return 0;
		} 
		cin >> m;
		for(int i = 1; i <= n; i++){
			a[i] = i;
		}
		for(int i = 1; i <= m; i++){
			cin >> x >> y;
			h(x, y);
		}
		for(int i = 1; i <= n; i++){
			for(int j = 1; j <= n; j++){
				if(find(i) != find(j)){////判断两个数是否在同一集合。
					ans++;
					h(i, j);
				}
			}
		}
		cout << ans << '\n';
	}
	return 0;
} 

思路:首先,用并查集将道路连起来。然后,如果两个村庄不在一个集合内,那么就将这两个集合连起来,并且道路数量加1。