-
题目描述:
-
省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可)。现得到城镇道路统计表,表中列出了任意两城镇间修建道路的费用,以及该道路是否已经修通的状态。现请你编写程序,计算出全省畅通需要的最低成本。
-
输入:
-
测试输入包含若干测试用例。每个测试用例的第1行给出村庄数目N ( 1< N < 100 );随后的 N(N-1)/2 行对应村庄间道路的成本及修建状态,每行给4个正整数,分别是两个村庄的编号(从1编号到N),此两村庄间道路的成本,以及修建状态:1表示已建,0表示未建。
当N为0时输入结束。
-
输出:
-
每个测试用例的输出占一行,输出全省畅通需要的最低成本。
-
样例输入:
-
3 1 2 1 0 1 3 2 0 2 3 4 0 3 1 2 1 0 1 3 2 0 2 3 4 1 3 1 2 1 0 1 3 2 1 2 3 4 1 0
-
样例输出:
-
3 1 0
-
来源:
//本题依然考查最小生成树,我采用的是Kruscal+并查集,但有个需要注意的地方:
//就是初始时有些道路已经修建,相当于其耗费为0,所以也要把它们纳入最后的生成树中;
//还有一种方法就是在输入时,若状态为1,直接置其费用为0,这样在并入时就不需要判断是否已建,
//因为在排序后就已经在最前,肯定会包含在最终的生成树中。
AC代码:
#include<stdio.h>
#include<algorithm>
using namespace std;
int p[100]; //存放节点的根节点,初始化为-1
struct Road { //道路结构体
int start;
int end;
int cost;
int flag; //标记是否已建
bool operator < (const Road &b) const { //重载排序时的比较函数,调用sort时,就不用第三个参数cmp了
return cost < b.cost;
}
}roads[5000];
int findRoot(int x) { //返回当前节点的根节点
if(p[x] == -1) return x;
else {
int tmp = findRoot(p[x]); //压缩路径,节约查找时间
p[x] = tmp;
return tmp;
}
}
int Kruscal(Road roads[], int m) {
sort(roads,roads+m); //按道路费用升序排列
int a, b, sum=0, i;
for(i=0; i<m; i++) {
a = findRoot(roads[i].start);
b = findRoot(roads[i].end);
if(a!=b) {
p[b] = a;
if(roads[i].flag == 0) //若已建,则无需加上其费用
sum += roads[i].cost;
}
}
return sum;
}
int main() {
//freopen("in.txt","r",stdin);
int n, m;
while(scanf("%d",&n) && n) {
m = n*(n-1)/2;
int i, a, b;
for(i=1; i<=n; i++) //初始化
p[i] = -1;
for(i=0; i<m; i++) {
scanf("%d %d %d %d",&roads[i].start,&roads[i].end,&roads[i].cost,&roads[i].flag);
if(roads[i].flag == 1) {
a = findRoot(roads[i].start);
b = findRoot(roads[i].end);
if(a!=b)
p[b] = a; //如果该道路已建,则并入最终的最小生成树(可以理解其费用为0)
}
}
printf("%d\n",Kruscal(roads,m));
}
return 0;
}