ZOJ2966

来源:互联网 发布:网络摄像机检测报告 编辑:程序博客网 时间:2024/05/17 12:53
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 integerT (1 <= T <= 50) which is the number of test cases. And it will be followed byT consecutive test cases.

In each test case, the first line contains two positive integers N andE (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 followE 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. IfK 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

13 30 1 50 2 01 2 9

Sample Output

5


最小生成树模板题。


我用的是Kruskal 算法:


#include<cstdio>#include<cstring>#include<algorithm>#define clr(x) memset(x, 0 sizeof(x));using namespace std;struct node{    int u, v, w;}N[20000];int pre[505];int n, m;bool cmp(node a, node b){    return a.w < b.w;}void init(){    for(int i = 0; i < 505; i++)        pre[i] = -1;}int Find(int x){    return pre[x] == -1? x : pre[x] = Find(pre[x]);}int kru(){    int cnt = 0;    int sum = 0;    for(int i = 0; i < m; i++)    {        int uu = Find(N[i].u);        int vv = Find(N[i].v);        if(uu != vv)        {            pre[uu] = vv;            sum += N[i].w;            cnt++;        }        if(cnt >= n - 1)        return sum;    }}int main(){    int T;    scanf("%d", &T);    while(T--)    {        init();        scanf("%d %d", &n, &m);        for(int i = 0; i < m; i++)        {            scanf("%d %d %d",&N[i].u, &N[i].v, &N[i].w);        }        sort(N, N + m, cmp);        int ans = kru();        printf("%d\n", ans);    }    return 0;}


0 0
原创粉丝点击