畅通工程 http://acm.hdu.edu.cn/showproblem.php?pid=1863
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 33927 Accepted Submission(s): 15013
Problem Description
省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可)。经过调查评估,得到的统计表中列出了有可能建设公路的若干条道路的成本。现请你编写程序,计算出全省畅通需要的最低成本。
Input
测试输入包含若干测试用例。每个测试用例的第1行给出评估的道路条数 N、村庄数目M ( < 100 );随后的 N
行对应村庄间道路的成本,每行给出一对正整数,分别是两个村庄的编号,以及此两村庄间道路的成本(也是正整数)。为简单起见,村庄从1到M编号。当N为0时,全部输入结束,相应的结果不要输出。
行对应村庄间道路的成本,每行给出一对正整数,分别是两个村庄的编号,以及此两村庄间道路的成本(也是正整数)。为简单起见,村庄从1到M编号。当N为0时,全部输入结束,相应的结果不要输出。
Output
对每个测试用例,在1行里输出全省畅通需要的最低成本。若统计数据不足以保证畅通,则输出“?”。
Sample Input
3 31 2 11 3 22 3 41 32 3 20 100
Sample Output
3?
#include <stdio.h>
#include <iostream>
#include <string.h>
#include <algorithm>
#include <math.h>
#include <vector>
#include <math.h>
using namespace std;
struct node
{
int a,b,p;
}s[105];
int fa[105];
int n,m;
int ranp[105]; //记录树的高度
int fin(int x)
{
if(x==fa[x])
return x;
else
return fa[x]=fin(fa[x]);
}
int cmp(node a,node b)
{
return a.p<b.p;
}
void unio(int x,int y)
{
if(ranp[x]<ranp[y]) 将矮的树连到高的树上
fa[x]=y;
else
{
fa[y]=x;
if(ranp[x]==ranp[y])
ranp[x]++;
}
}
int kul()
{
int i,j,res=0,ege=0;
for(i=0;i<n && ege!=m-1;i++) //ege记录已连接的道路条数
{
int q=fin(s[i].a);
int p=fin(s[i].b);
if(p!=q) //s[i].a 与s[i].b 未连接,将它们连接
{
unio(p,q);
ege++;
res+=s[i].p;
}
}
if(ege==m-1)
return res;
return -1;
}
int main()
{
int i,j;
while(~scanf("%d%d",&n,&m) && n) //n为道路数目,m为村庄
{
for(i=0;i<n;i++)
{
scanf("%d%d%d",&s[i].a,&s[i].b,&s[i].p);
s[i].a--;
s[i].b--;
}
for(i=0;i<m;i++)
{
fa[i]=i;ranp[i]=0;
}
sort(s,s+n,cmp); //将s[n]按道路的权值大小排序
int ans=kul();
if(ans==-1)
printf("?\n");
else
printf("%d\n",ans);
}
return 0;
}

2940

被折叠的 条评论
为什么被折叠?



