还是畅通工程

Problem Description
某省调查乡村交通状况,得到的统计表中列出了任意两村庄间的距离。省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可),并要求铺设的公路总长度为最小。请计算最小的公路总长度。
 
Input
测试输入包含若干测试用例。每个测试用例的第1行给出村庄数目N ( < 100 );随后的N(N-1)/2行对应村庄间的距离,每行给出一对正整数,分别是两个村庄的编号,以及此两村庄间的距离。为简单起见,村庄从1到N编号。 当N为0时,输入结束,该用例不被处理。
 
Output
对每个测试用例,在1行里输出最小的公路总长度。
 
Sample Input
3 1 2 1 1 3 2 2 3 4 4 1 2 1 1 3 4 1 4 1 2 3 3 2 4 2 3 4 5 0
 
Sample Output
3 5
题意:n个点,给出n个点任意两点之间的距离。求联通n个点的最短距离。
题解:最小生成树问题,可用kruskal算法+并查集求解
#include<stdio.h>
#include<iostream>
#include<string.h>
#include<algorithm>
using namespace std;
int p[105],n,sum;
void init()
{
 int i;
 for(i=1;i<=n;i++) p[i]=i;
}
int find(int x)
{
 if(x==p[x]) return x;
 else return p[x]=find(p[x]);
}
bool unioner(int x,int y)
{
 int xa=find(x);
 int xb=find(y);
 if(xa==xb) return false;
 else p[xa]=xb;
    return true;
}
struct lmx{
 int v;
 int w;
 int cost;
 bool operator<(const lmx s)const{
  return cost<s.cost;
 }
};
lmx lm[8000];
int main()
{
 int i;
    while(scanf("%d",&n),n)
 {
  init();
  for(i=0;i<n*(n-1)/2;i++)
  {
   scanf("%d %d %d",&lm[i].v,&lm[i].w,&lm[i].cost);
  }
  sort(lm,lm+(n*(n-1)/2));
  sum=0;
        for(i=0;i<(n-1)*n/2;i++)
  {
          int xx=lm[i].v;
    int yy=lm[i].w;
    if(unioner(xx,yy)) sum+=lm[i].cost;
  }
  printf("%d\n",sum);
 }
 return 0;
}
 
posted @ 2013-09-16 16:39  forevermemory  阅读(123)  评论(0编辑  收藏  举报