Earthquake

点击打开链接
Description

After the big earthquake, a lot of roads have been destroyed, some towns are disconnected with each other. 

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

For each test case, you should output a line contains a number denotes the minimal time need to rebuild the roads so that all the towns are connected.

Sample Input

2
3 3
1 2 3
2 3 3
3 1 7
3 3
1 2 3
2 3 3
3 1 1

Sample Output

6
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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值