欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

【ZOJ 2966】Build The Electric System(最小生成树 Kruskal )

程序员文章站 2022-06-21 15:00:23
Description 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 ......

Description

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, 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 Kto 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

题意

给出一个无向边带权图,输出最小生成树

#include<iostream>
#include<algorithm>
using namespace std;
int p[10005],n,e;
struct edge
{
    int x,y,w;
}a[10005];
int cmp(edge a,edge b)
{
    return a.w<b.w;
}
int find(int r)
{
    if(p[r]!=r)
    p[r]=find(p[r]);
    return p[r];
}
int k()
{
    sort(a,a+e,cmp);              //一定要以边edge排序啊!!!
    int ans=0,i;
    for(i=0;i<e;i++)
    {
        int fx=find(a[i].x),fy=find(a[i].y);
        if(fx!=fy)
        {
            p[fx]=fy;
            ans+=a[i].w;
        } 
    }
    return ans;
}
int main()  
{  
    int t,i;
    cin>>t;
    while(t--)
    {
        cin>>n>>e;
        for(i=0;i<=n;i++)
            p[i]=i;
        for(i=0;i<e;i++)
            scanf("%d%d%d",&a[i].x,&a[i].y,&a[i].w);
        printf("%d\n",k());
    } 
    return 0;
}