某地区经过对城镇交通状况的调查,得到现有城镇间快速道路的统计数据,并提出“畅通工程”的目标:使整个地区任何两个城镇间都可以实现快速交通(但不一定有直接的快速道路相连,只要互相间接通过快速路可达即可)。现得到城镇道路统计表,表中列出了任意两城镇间修建快速路的费用,以及该道路是否已经修通的状态。现请你编写程序,计算出全地区畅通需要的最低成本。
输入格式:
输入的第一行给出村庄数目N (1);随后的(行对应村庄间道路的成本及修建状态:每行给出4个正整数,分别是两个村庄的编号(从1编号到N),此两村庄间道路的成本,以及修建状态 — 1表示已建,0表示未建。
输出格式:
输出全省畅通需要的最低成本。
输入样例:
4
1 2 1 1
1 3 4 0
1 4 1 1
2 3 3 0
2 4 2 1
3 4 5 0
输出样例:
3
看了别人博客,把已经建成的路的权值设成 0 ,非常巧妙
#include<stdio.h>
#include<algorithm>
using namespace std;
struct node{
int c1;
int c2;
int cost;
int flag;
};
bool cmp(node a,node b){
return a.cost<b.cost;
}
int tree[1010];
void init(int n){
int i;
for(i=1;i<=n;i++){
tree[i]=-1;
}
}
int findroot(int x){
if(tree[x]==-1)return x;
return tree[x]=findroot(tree[x]);
}
int main(){
int n,m,i;
scanf("%d",&n);
m=n*(n-1)/2;
node stu[m];
for(i=0;i<m;i++){
scanf("%d %d %d %d",&stu[i].c1,&stu[i].c2,&stu[i].cost,&stu[i].flag);
if(stu[i].flag){
stu[i].cost=0;
}
}
sort(stu,stu+m,cmp);
int sum=0;
init(n);
for(i=0;i<m;i++){
int a=findroot(stu[i].c1);
int b=findroot(stu[i].c2);
if(a!=b){
tree[a]=b;
sum=sum+stu[i].cost;
}
}
int cou=0;
for(i=1;i<=n;i++){
if(tree[i]==-1){
cou++;
}
}
if(cou!=1){
printf("Impossible");
}
else{
printf("%d",sum);
}
}