| ||||||||||
| Online Judge | Problem Set | Authors | Online Contests | User | ||||||
|---|---|---|---|---|---|---|---|---|---|---|
| Web Board Home Page F.A.Qs Statistical Charts | Current Contest Past Contests Scheduled Contests Award Contest | |||||||||
全裸的题目!#include <stdio.h>
#include <string.h>
#include <stdlib.h>
const int size = 5000;
int father[size];
typedef struct node
{
int s;
int e;
int len;
}Node;
Node road[size];
int cmp(const void *_a,const void *_b)
{
Node *a=(Node*)_a;
Node *b=(Node*)_b;
return a->len-b->len;
}
void init_set(int n)
{
int i;
for(i=1;i<=n;i++)
father[i]=i;
}
int dfs_set(int x)
{
return father[x]==x?x:dfs_set(father[x]);
}
int union_set(int a,int b)
{
a=dfs_set(a);
b=dfs_set(b);
if(a==b)
return 0;
else
{
if(a>b)
father[a]=b;
else
father[b]=a;
return 1;
}
}
int main()
{
int m,n,i,j,k,sum,count;
while(scanf("%d",&n)!=EOF&&n)
{
scanf("%d",&m);
for(k=0;k<m;k++)
scanf("%d %d %d",&road[k].s,&road[k].e,&road[k].len);
init_set(n);
qsort(road,m,sizeof(road[1]),cmp);
sum=0;
count=0;
for(i=0;i<m;i++)
{
if(union_set(road[i].s,road[i].e))
{
sum+=road[i].len;
count++;
}
if(count==n-1)
break;
}
printf("%d\n",sum);
}
return 1;
}
Followed by: Post your reply here: |
All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator