TOJ 1540 Build The Electric System 并查集

1540: Build The Electric System

描述

 

In last winter, there was a big snow storm in South China. The electric system was damaged seriously. Lots of power lines were broken and lots of villages lost contact with the main power grid. The government wants to reconstruct the electric system as soon as possible. So, as a professional programmer, you are asked to write a program to calculate the minimum cost to reconstruct the power lines to make sure there's at least one way between every two villages.

 

输入

 

Standard input will contain multiple test cases. The first line of the input is a single integer T (1 <= T <= 50) which is the number of test cases. And it will be followed by T consecutive test cases.

In each test case, the first line contains two positive integers N and E (2 <= N <= 500, N <= E <= N * (N - 1) / 2), representing the number of the villages and the number of the original power lines between villages. There follow E lines, and each of them contains three integers, ABK (0 <= AB < N, 0 <= K < 1000). A and B respectively means the index of the starting village and ending village of the power line. If K is 0, it means this line still works fine after the snow storm. If K is a positive integer, it means this line will cost K to reconstruct. There will be at most one line between any two villages, and there will not be any line from one village to itself.

 

输出

For each test case in the input, there's only one line that contains the minimum cost to recover the electric system to make sure that there's at least one way between every two villages.

样例输入

1
3 3
0 1 5
0 2 0
1 2 9

样例输出

5

并查集模板走一下~

#include<stdio.h>
#include<string.h>
#include<math.h>
#include<iostream>
#include<string>
#include<algorithm>
#include<map>
#include<set>
#include<queue>
#include<vector>
using namespace std;
#define inf 0x3f3f3f3f
#define LL long long
int father[505];
struct p
{
	int a,b,c;
}f[125050];
int cmp(p z,p z1)
{
  return z.c<z1.c?1:0;	
} 
int find(int x)     
{  
	int r=x,i=x,j;
	while(father[r]!=r)
	r=father[r];
	while(father[i]!=i)
	j=father[i],father[i]=r,i=j;
	return r;
}
int main()
{
	int t,n,m,i,j,s,a,b;
	scanf("%d",&t);
	while(t--)
	{
		s=0;
		scanf("%d%d",&n,&m);
		for(i=0;i<=n;i++)  
		father[i]=i; 
		for(i=0;i<m;i++)
  		scanf("%d%d%d",&f[i].a,&f[i].b,&f[i].c);
  		sort(f,f+m,cmp); 
  		for(i=0;i<m;i++)
	  	{
			a=find(f[i].a);
			b=find(f[i].b);
			if(a!=b)
			{
				s+=f[i].c;
				father[a]=b;
			}
	  	}
	  	printf("%d\n",s);
	}	
}

猜你喜欢

转载自blog.csdn.net/thewise_lzy/article/details/81235349