第二周HDU-1232题解

问题链接:HDU-1232

问题简述

输入两个正整数n,m,n为城镇数对应城镇编号,m为两座城镇之间的道路数,输入m组,每组两个城镇编号,表示之间有道路连通,求还需要建多少条道路能使每个城镇之间,不一定有直接的道路相连,只要互相间接通过道路可达即可。

思路

上周的周赛题,当时看了题目没有想法,后来看了帽子学长发的题解,百度简单的学了查并集,然后运用查并集进行解题。

AC通过的C++语言程序如下:

#include<iostream>
using namespace std;
int city[1000];
void build(int, int);
int find(int);
int main()
{
	int n, m, a, b;
	while (cin >> n)
	{
		if (n == 0) break;
		cin >> m;
		int t = 0;
		for (int i = 0; i < n; i++)
			city[i] = i;
		for (int i = 0; i < m; i++)
		{
			cin >> a >> b;
			build(a - 1, b - 1);
		}
		for (int i = 0; i < n; i++)
			if (city[i] == i) t++;
		cout << t - 1 << endl;
	}
	return 0;
}
void build(int x, int y)
{
	if (find(city[x]) != find(city[y]))
		city[find(city[y])] = find(city[x]);
 }
int find(int x)
{
	if (city[x] == x) return x;
	else return find(city[city[x]]);
}

猜你喜欢

转载自blog.csdn.net/weixin_43970556/article/details/84976972