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, A, B, K (0 <= A, B < 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<bits/stdc++.h>
using namespace std;
struct node
{
int A,B,K;
}E[20001];
int f[505];
int findit(int x)
{
return f[x]==x?x:findit(f[x]);
}
bool cmp(node x,node y)
{
return x.K<y.K;
}
int main()
{
int T;
cin>>T;
while(T–)
{
int N,M;
cin>>N>>M;
for (int i=0;i<N;i++)
{
f[i]=i;
}
for (int i=0;i<M;i++)
{
cin>>E[i].A>>E[i].B>>E[i].K;
}
sort(E,E+M,cmp);
int ans=0;
for (int i=0;i<M;i++)
{
int fx=findit(E[i].A);
int fy=findit(E[i].B);
if (fx!=fy)
{
ans+=E[i].K;
f[fx]=fy;
}
}
cout<<ans<<endl;
}
return 0;
}

发布了40 篇原创文章 · 获赞 0 · 访问量 683

猜你喜欢

转载自blog.csdn.net/Skynamer/article/details/103406068