hdoj problem 1233 还是畅通工程(并查集+动态规划)

来源:互联网 发布:游民星空mac游戏 编辑:程序博客网 时间:2024/04/30 10:18

还是畅通工程

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 26782    Accepted Submission(s): 11954
http://acm.hdu.edu.cn/showproblem.php?pid=1233

Problem Description
某省调查乡村交通状况,得到的统计表中列出了任意两村庄间的距离。省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可),并要求铺设的公路总长度为最小。请计算最小的公路总长度。
 

Input
测试输入包含若干测试用例。每个测试用例的第1行给出村庄数目N ( < 100 );随后的N(N-1)/2行对应村庄间的距离,每行给出一对正整数,分别是两个村庄的编号,以及此两村庄间的距离。为简单起见,村庄从1到N编号。
当N为0时,输入结束,该用例不被处理。
 

Output
对每个测试用例,在1行里输出最小的公路总长度。
 

Sample Input
31 2 11 3 22 3 441 2 11 3 41 4 12 3 32 4 23 4 50
 

Sample Output
35
Hint
Hint
Huge input, scanf is recommended.
 

Source
浙大计算机研究生复试上机考试-2006年
 

Recommend
JGShining   |   We have carefully selected several similar problems for you:  1102 1875 1879 1301 1162
/*本题与hdoj1232 畅通工程 类似,只不过是将该题中的m换了*/
#include<cstdio>
#include<cstring>
#include<stdlib.h>
#include<algorithm>
using namespace std; 
int preroot[105];
struct node
{
int p1;
int p2; 
int price;
};
node way[10000];
int cmp(node a,node b)
{
return a.price<b.price;
}
int find(int x)
{
int root=x;
while(preroot[root]!=root) 
 root=preroot[root];

int t=x,r;
while(t!=root)
{
r=preroot[t]; 
preroot[t]=root;
t=r;
}
return root;
}


int join(int x,int y) 
{
int fx=find(x);
int fy=find(y);
if(fx!=fy)       
              
{
 preroot[fx]=fy;
 return 1;
}
return 0;  
}

int main()
{  
  memset(preroot,0,sizeof(preroot));
  memset(preroot,0,sizeof(preroot));
  int n;
  while(scanf("%d",&n)&&n)
  {
  int i,j;
  for(i=0;i<=n;i++) 
   preroot[i]=i;

   
   for(i=0;i<n*(n-1)/2;i++)
     scanf("%d%d%d",&way[i].p1,&way[i].p2,&way[i].price);
     
     sort(way,way+n*(n-1)/2,cmp);
     
     int sum=0,count=0;
      for(i=0;i<n*(n-1)/2;i++)
      {
      if(count==n-1)
       break;
      if(join(way[i].p1,way[i].p2))
       {
       count++;
       sum+=way[i].price;
       }
      }  
       
          printf("%d\n",sum);
  }
  return 0;
0 0