畅通工程
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 60037 Accepted Submission(s): 32114
Problem Description
测试输入包含若干测试用例。每个测试用例的第1行给出两个正整数,分别是城镇数目N ( < 1000 )和道路数目M;随后的M行对应M条道路,每行给出一对正整数,分别是该条道路直接连通的两个城镇的编号。为简单起见,城镇从1到N编号。
注意:两个城市之间可以有多条道路相通,也就是说
3 3
1 2
1 2
2 1
这种输入也是合法的
当N为0时,输入结束,该用例不被处理。
对每个测试用例,在1行里输出最少还需要建设的道路数目。
4 2
1 3
4 3
3 3
1 2
1 3
2 3
5 2
1 2
3 5
999 0
0
1
0
2
998
Source
问题链接:HDU1232 畅通工程。
问题简述:
输入n和m,分别表示城镇的数量和城镇间道路的数量。再输入m个数对s和d表示城镇s到d有道路连通。问还需要修多少条道路才能够把这些城镇都连通起来。
问题分析:
这是一个有关图的连通性问题,可以用并查集来解决。并查集中,连通的各个结点都会指向相同的根。
程序说明:
程序中,构建一个用并查集,使得相互连通的子图指向相同的根,发现到两个互不相连的子图时,增加一条边使之相连。
代码不够简洁,又写了一个简洁版。
AC的C++语言程序(简洁版)如下:
/* HDU1232 畅通工程 */
#include <bits/stdc++.h>
using namespace std;
const int N = 1000;
int f[N + 1], fcnt;
void UFInit(int n)
{
for(int i = 1; i <=n; i++)
f[i] = i;
fcnt = n;
}
int Find(int a) {
return a == f[a] ? a : f[a] = Find(f[a]);
}
void Union(int a, int b)
{
a = Find(a);
b = Find(b);
if (a != b) {
f[a] = b;
fcnt--;
}
}
int main()
{
int n, m, u, v;
while(cin >> n && n != 0) {
// 初始化并查集
UFInit(n);
// 输入边(城镇道路),构造并查集
cin >> m;
while(m--) {
cin >> u >> v;
Union(u, v);
}
// 输出结果
cout << fcnt - 1 << endl;
}
return 0;
}
AC的C++语言程序如下:
/* HDU1232 畅通工程 */
#include <iostream>
#include <vector>
using namespace std;
// 并查集类
class UF {
private:
vector<int> v;
public:
UF(int n) {
for(int i=0; i<=n; i++)
v.push_back(i);
}
int Find(int x) {
for(;;) {
if(v[x] != x)
x = v[x];
else
return x;
}
}
bool Union(int x, int y) {
x = Find(x);
y = Find(y);
if(x == y)
return false;
else {
v[x] = y;
return true;
}
}
};
int main()
{
int n, m, src, dest, root, count;
while(cin >> n && n != 0) {
UF uf(n);
cin >> m;
// 输入边(城镇道路),构造并查集
while(m--) {
cin >> src >> dest;
if(uf.Find(src) != uf.Find(dest))
uf.Union(src, dest);
}
// 逐个结点(城镇)检查是否联通,如果不联通则修一条道路使其联通
count = 0;
root = uf.Find(1);
for(int i=2; i<=n; i++)
if(uf.Find(i) != root) {
uf.Union(i, 1);
count++;
}
// 输出结果
cout << count << endl;
}
return 0;
}