您的位置:首页 > 其它

习题8.4 畅通工程之最低成本建设问题(30 分)

2017-09-22 21:42 801 查看


习题8.4 畅通工程之最低成本建设问题(30 分)

某地区经过对城镇交通状况的调查,得到现有城镇间快速道路的统计数据,并提出“畅通工程”的目标:使整个地区任何两个城镇间都可以实现快速交通(但不一定有直接的快速道路相连,只要互相间接通过快速路可达即可)。现得到城镇道路统计表,表中列出了有可能建设成快速路的若干条道路的成本,求畅通工程需要的最低成本。


输入格式:

输入的第一行给出城镇数目N (1<N≤1000)和候选道路数目M≤3N;随后的M行,每行给出3个正整数,分别是该条道路直接连通的两个城镇的编号(从1编号到N)以及该道路改建的预算成本。


输出格式:

输出畅通工程需要的最低成本。如果输入数据不足以保证畅通,则输出“Impossible”。


输入样例1:

6 15
1 2 5
1 3 3
1 4 7
1 5 4
1 6 2
2 3 4
2 4 6
2 5 2
2 6 6
3 4 6
3 5 1
3 6 1
4 5 10
4 6 8
5 6 3


输出样例1:

12


输入样例2:

5 4
1 2 1
2 3 2
3 1 3
4 5 4


输出样例2:

Impossible


并查集+K

#include<stdio.h>
#include<algorithm>
using namespace std;
struct node{
int c1;
int c2;
int cost;
};
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 %d",&n,&m);
node stu[m];
for(i=0;i<m;i++){
scanf("%d %d %d",&stu[i].c1,&stu[i].c2,&stu[i].cost);
}
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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: