您的位置:首页 > 产品设计 > UI/UE

ZOJ2966-Build The Electric System

2017-04-11 23:00 411 查看
Build The Electric System
Time Limit: 2 Seconds      Memory Limit: 65536 KB

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.
Input
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.
Output
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.
Sample Input

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


Sample Output

5


Author: ZHOU, Ran
Source: The 5th Zhejiang Provincial Collegiate Programming Contest

题意:有n个村庄,有m条有权值的无向边,问最少话费多少才能使所有点相连通

解题思路:最小生成树

#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
#include <queue>
#include <vector>
#include <set>
#include <stack>
#include <map>
#include <climits>

using namespace std;
#define LL long long

struct node
{
int s,e,w;
}x[250009];
int f[509];

int cmp(node x,node y)
{
return x.w<y.w;
}

int Find(int x)
{
if(f[x]==x) return x;
else return f[x]=Find(f[x]);
}

int main()
{
int t,n,m;
scanf("%d",&t);
while(t--)
{
scanf("%d %d",&n,&m);
for(int i=0;i<m;i++)
scanf("%d %d %d",&x[i].s,&x[i].e,&x[i].w);
for(int i=0;i<n;i++) f[i]=i;
sort(x,x+m,cmp);
int ans=0;
for(int i=0;i<m;i++)
{
int ss=Find(x[i].s),ee=Find(x[i].e);
if(ss!=ee)
{
ans+=x[i].w;
f[ss]=ee;
}
}
printf("%d\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: