继续畅通工程
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 26913 Accepted Submission(s): 11362
Problem Description
省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可)。现得到城镇道路统计表,表中列出了任意两城镇间修建道路的费用,以及该道路是否已经修通的状态。现请你编写程序,计算出全省畅通需要的最低成本。
Input
测试输入包含若干测试用例。每个测试用例的第1行给出村庄数目N ( 1< N < 100 );随后的 N(N-1)/2 行对应村庄间道路的成本及修建状态,每行给4个正整数,分别是两个村庄的编号(从1编号到N),此两村庄间道路的成本,以及修建状态:1表示已建,0表示未建。
当N为0时输入结束。
当N为0时输入结束。
Output
每个测试用例的输出占一行,输出全省畅通需要的最低成本。
Sample Input
31 2 1 01 3 2 02 3 4 031 2 1 01 3 2 02 3 4 131 2 1 01 3 2 12 3 4 10
Sample Output
310
Author
ZJU
Source
问题链接:HDU1879 继续畅通工程。
问题描述:参见上文。
问题分析:
这是一个最小生成树的为问题,解决的算法有Kruskal(克鲁斯卡尔)算法和Prim(普里姆) 算法。
程序说明:
本程序使用Kruskal算法实现。有关最小生成树的问题,使用克鲁斯卡尔算法更具有优势,只需要对所有的边进行排序后处理一遍即可。程序中使用了并查集,用来判定加入一条边后会不会产生循环。程序中,图采用边列表的方式存储,按边的权从小到大顺序放在优先队列中,省去了排序。
代码不够简洁,又写了一个简洁版。
AC的C++语言程序(简洁版)如下:
/* HDU1879 继续畅通工程 */
#include <iostream>
#include <queue>
#include <stdio.h>
using namespace std;
const int N = 100;
int f[N + 1];
void UFInit(int n)
{
for(int i = 1; i <=n; i++)
f[i] = i;
}
int Find(int a) {
return a == f[a] ? a : f[a] = Find(f[a]);
}
bool Union(int a, int b)
{
a = Find(a);
b = Find(b);
if (a != b) {
f[a] = b;
return true;
} else
return false;
}
struct edge {
int src, dest, cost;
bool operator < (const edge& n) const {
return cost > n.cost;
}
};
int main()
{
int n, ecount, status;
edge e;
while(scanf("%d", &n) != EOF && n) {
priority_queue<edge> q; // 优先队列,用于存储边列表
UFInit(n);
ecount = n * (n - 1) / 2;
while(ecount--) {
scanf("%d%d%d%d", &e.src, &e.dest, &e.cost, &status);
if(status == 1)
Union(e.src, e.dest);
else
q.push(e);
}
// Kruskal算法:获得最小生成树
int ans=0, count=0;
while(!q.empty()) {
e = q.top();
q.pop();
if(Union(e.src, e.dest)) {
count++;
ans += e.cost;
}
if(count == n - 1)
break;
}
// 输出结果
printf("%d\n", ans);
}
return 0;
}
/* HDU1879 继续畅通工程 */
#include <iostream>
#include <queue>
#include <cstdio>
using namespace std;
const int MAXN = 100;
// 并查集
int v[MAXN+1];
class UF {
public:
UF() {}
// 压缩
int Find(int x) {
if(x == v[x])
return x;
else
return v[x] = Find(v[x]);
}
bool Union(int x, int y) {
x = Find(x);
y = Find(y);
if(x == y)
return false;
else {
v[x] = y;
return true;
}
}
void reset(int n) {
for(int i=0; i<=n; i++)
v[i] = i;
}
};
struct edge {
int src, dest, cost;
bool operator < (const edge& n) const {
return cost > n.cost;
}
};
int main()
{
int n, ecount, status;
UF uf;
edge e;
while(scanf("%d", &n) != EOF && n) {
priority_queue<edge> q; // 优先队列,用于存储边列表
uf.reset(n);
ecount = n * (n - 1) / 2;
while(ecount--) {
scanf("%d%d%d%d", &e.src, &e.dest, &e.cost, &status);
if(status == 1)
uf.Union(e.src, e.dest);
else
q.push(e);
}
// Kruskal算法:获得最小生成树
int ans=0, count=0;
while(!q.empty()) {
e = q.top();
q.pop();
if(uf.Union(e.src, e.dest)) {
count++;
ans += e.cost;
}
if(count == n - 1)
break;
}
// 输出结果
printf("%d\n", ans);
}
return 0;
}