习题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);
}
}
相关文章推荐
- 7-12 畅通工程之最低成本建设问题(30 point(s)) 【PRIME】
- 畅通工程之最低成本建设问题(30 分)
- 7-2 畅通工程之最低成本建设问题(30 分)
- 畅通工程之最低成本建设问题(最小生成树(Kruskal)+并查集)
- 5-13 畅通工程之最低成本建设问题 (30分)(这个是补上去的7月5号)
- 六度空间 地下迷宫探索 哈利·波特的考试 旅游规划 畅通工程之最低成本建设问题
- PTA 5-6 畅通工程之最低成本建设问题【Kruskal】
- PAT 5-6 畅通工程之最低成本建设问题 【Prim】
- 同【(前向星建图)hdu1873 畅通工程】畅通工程之最低成本建设问题
- 5-4 畅通工程之最低成本建设问题 (30分)
- 畅通工程之最低成本建设问题
- Kruskal算法-畅通工程之最低成本建设问题.cpp
- PTA5-2 畅通工程之最低成本建设问题 (克鲁斯卡尔)
- 习题8.5 畅通工程之局部最小花费问题(35 分)
- 信息化建设工程的有效成本及定价分析(1)
- HDU 1875 畅通工程再续(最小生成树问题)Prim算法
- <hdu - 1232> 畅通工程 并查集问题 (注意中的细节)
- 信息化建设工程的有效成本及定价分析(2)
- 7-1 畅通工程之局部最小花费问题(35 分)
- HDU 1875 畅通工程再续 最小生成树问题