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

来源:互联网 发布:历史数据库 英文 编辑:程序博客网 时间:2024/04/29 06:39

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

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

输入格式:

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

输出格式:

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

输入样例1:

6 151 2 51 3 31 4 71 5 41 6 22 3 42 4 62 5 22 6 63 4 63 5 13 6 14 5 104 6 85 6 3

输出样例1:

12

输入样例2:

5 41 2 12 3 23 1 34 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);}}



阅读全文
0 0
原创粉丝点击