问题描述
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 costK 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
分析:一开始看见这道题是图论问题,我就先放放,后来看见一些人AC了,果断努力拿下,WA7次终于过了。最后的思路是并查集。
大体题意:n个村庄之间有路,但被破坏了,有些没有被破坏。现在问题是,修每条路有一个费用,问最低费用是多少,使得任何两个村庄可以到达。其实也是一个最小生成树问题。我用的并查集思路是:先对路的费用进行排序,然后从最少费用的边开始添加,如果拥有同一个父亲,说明成圈了,就放弃添加。这个思路其实就是最小生成树的kruskal(克鲁斯卡尔)算法。
LANGUAGE:C++
CODE:
#include <iostream>
#include <string.h>
#include <algorithm>
using namespace std;
const int maxn=500005;
int par[maxn];
bool flag;
struct node{
int a,b,k;
}mar[maxn];
int cmp(node a,node b)
{
return a.k<b.k;
}
void init(int n)
{
for(int i=0;i<n;i++){
par[i]=i;
}
return ;
}
int find(int x)
{
if(par[x]==x){
return x;
}
else{
return par[x]=find(par[x]);
}
return 0;
}
void unite(int x,int y)
{
x=find(x);
y=find(y);
if(x==y)
return ;
else{
par[x]=y;
flag=true;
}
return ;
}
int main()
{
int t;
cin>>t;
while(t--){
memset(par,0,sizeof(par));
memset(mar,0,sizeof(mar));
int n,m,ans=0;
cin>>n>>m;
init(n);
for(int i=0;i<m;i++){
cin>>mar[i].a>>mar[i].b>>mar[i].k;
}
sort(mar,mar+m,cmp);
// for(int i=0;i<m;i++){
// cout<<mar[i].a<<mar[i].b<<mar[i].k<<endl;
// }
for(int i=0;i<m;i++){
flag=false;
unite(mar[i].a,mar[i].b);
if(flag)
ans+=mar[i].k;
}
cout<<ans<<endl;
}
return 0;
}