省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可)。现得到城镇道路统计表,表中列出了任意两城镇间修建道路的费用,以及该道路是否已经修通的状态。现请你编写程序,计算出全省畅通需要的最低成本。
输入描述:
测试输入包含若干测试用例。每个测试用例的第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
板子题,不同点:已经修建好的公路优先级高,把其成本设为0
#include<bits/stdc++.h>
using namespace std;
struct Edge{
int from;
int to;
int length;
int is_build;
};
const int MAXN=101;
Edge edge[MAXN*MAXN];
int father[MAXN];
int height[MAXN];
void init(int n){
for(int i=0;i<=n;i++){
father[i]=i;
height[i]=0;
}
}
int find(int x){
if(x!=father[x]){
x=find(father[x]);
}
return x;
}
void union1(int x,int y){
int x1=find(x);
int y1=find(y);
//两个结点不在一个集合里
if(x1!=y1){
if(height[x1]<height[y1]){
father[x1]=y1;
}
else if(height[x1]>height[y1]){
father[y1]=x1;
}
else if(height[x1]==height[y1]){
father[y1]=x1;
height[x1]++;
}
}
}
bool bmp(Edge a,Edge b){
//这一点雷到我。。。
//if(a.length!=b.length){
//return a.length<b.length;
//}
//用上面的比较方法只有80%的数据能通过
//绞尽脑汁看其他地方代码都没错,才想到改这儿
return a.length<b.length;
}
int Kruscal(int n,int edgenum){
init(n);
int result=0;
sort(edge,edge+edgenum,bmp);
for(int i=0;i<edgenum;i++){
Edge current;
current=edge[i];
if(find(current.from)!=find(current.to)){
union1(current.from,current.to);
result+=current.length;
}
}
return result;
}
int main(){
int n,edgenum;
while(cin>>n){
if(n==0){
break;
}
edgenum=n*(n-1)/2;
for(int i=0;i<edgenum;i++){
cin>>edge[i].from>>edge[i].to>>edge[i].length>>edge[i].is_build;
if(edge[i].is_build==1){
edge[i].length=0;
}
}
int result=Kruscal(n,edgenum);
cout<<result<<endl;
}
return 0;
}