点击打开链接
Description
In order to save the trapped as soon as possible, we need to try our best to rebuild the roads, and make sure all the towns will be reconnected(that is any villages is connected to the others with a clear route at least).
Unfortunately, we have only one team to rebuild the roads. Now,please tell us how long do you think these roads can be reconnected.
Input
The first line contains a number T denotes the number of test case.
For each test case,
In the first line, you will get two number N (1<=N<=1000) and M(1<=M<=N*N), denotes the number of towns and the number of roads.
The next M lines, each contains three number A,B,C, denotes there is a road between A and B that needed C (1<=C<=1000) minutes to rebuild.
Output
Sample Input
3 3
1 2 3
2 3 3
3 1 7
3 3
1 2 3
2 3 3
3 1 1
Sample Output
4
¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥
#include<iostream> #include<string.h>
#include<stdio.h>
#include<stdlib.h>
#include<algorithm>
using namespace std;
struct node
{
int l,r,value;
}g[1000050];
int cmp(const node&a,const node&b)
{
return a.value<b.value;
}
int set[1005];
//int used[1005];
int find(int x)
{
if(x!=set[x])
set[x]=find(set[x]);
return set[x];
}
void merge(int x,int y)
{
int fx,fy;
fx=find(x);
fy=find(y);
if(fx==fy)
return;
if(fx>fy)
{
set[fx]=fy;
}
else
{
set[fy]=fx;
}
}
int main()
{
int i,j,k,m,n,sum,ncase;
scanf("%d",&ncase);
while(ncase--)
{
scanf("%d%d",&m,&n);
for(i=0;i<m;i++)
{
set[i]=i;
}
for(i=0;i<n;i++)
{
scanf("%d%d%d",&g[i].l,&g[i].r,&g[i].value);
}
sort(g,n+g,cmp);
/*for(i=0;i<n;i++)
{
printf("%d %d %d\n",g[i].l,g[i].r,g[i].value);
}*/
int h=0;
sum=0;
for(i=0;i<n;i++)
{
if(find(g[i].l)!=find(g[i].r))
{
merge(g[i].l,g[i].r);
sum+=g[i].value;
h++;
}
}
printf("%d\n",sum);
}
return 0;
}