您的位置:首页 > 其它

HDU1863 畅通工程 【图论】【最小生成树】

2017-07-12 10:10 375 查看
【Problem Description】

省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可)。经过调查评估,得到的统计表中列出了有可能建设公路的若干条道路的成本。现请你编写程序,计算出全省畅通需要的最低成本。

【Input】

测试输入包含若干测试用例。每个测试用例的第1行给出评估的道路条数 N、村庄数目M ( < 100 );随后的 N

行对应村庄间道路的成本,每行给出一对正整数,分别是两个村庄的编号,以及此两村庄间道路的成本(也是正整数)。为简单起见,村庄从1到M编号。当N为0时,全部输入结束,相应的结果不要输出。

【Output】

对每个测试用例,在1行里输出全省畅通需要的最低成本。若统计数据不足以保证畅通,则输出“?”。

【Sample Input】

3 3

1 2 1

1 3 2

2 3 4

1 3

2 3 2

0 100

【Sample Output】

3

?

【题解】

裸的最小生成树

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N=100;
int head[N+5],num,father[N+5];
int n,m;
struct edge
{
int u,v,w;
int next;
edge(){next=-1;}
}ed[4*N+5];
void build(int u,int v,int w)
{
ed[++num].u=u;
ed[num].v=v;
ed[num].w=w;
ed[num].next=head[u];
head[u]=num;
}
int getfather(int a)
{
return father[a]==a?a:getfather(father[a]);
}
void unionn(int a,int b)
{
father[getfather(b)]=getfather(a);
}
bool cmp(edge a,edge b)
{
return a.w<b.w;
}
int kruskal()
{
int ans=0,tot=0;
sort(ed+1,ed+1+num,cmp);
for(int i=1;i<=m;i++)
father[i]=i;
for(int i=1;i<=num;i++)
{
if(getfather(ed[i].v)==getfather(ed[i].u))continue;
else unionn(ed[i].v,ed[i].u);
++tot;
ans+=ed[i].w;
if(tot==m-1)break;
}
if(tot==m-1)return ans;
else return -1;
}
int main()
{
while(scanf("%d",&n)&&n)
{
num=0;
memset(head,-1,sizeof(head));
scanf("%d",&m);
for(int i=1;i<=n;i++)
{
int u,v,w;
scanf("%d%d%d",&u,&v,&w);
build(u,v,w);
build(v,u,w);
}
int ans=kruskal();
if(ans==-1)printf("?\n");
else printf("%d\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: