zoukankan      html  css  js  c++  java
  • CDOJ 145 Earthquake

    After the big earthquake, a lot of roads have been destroyed, some towns are disconnected with each other.

    In order to save the trapped as soon as possible, we need to try our best to rebuild the roads, and make sure all the towns will be reconnected(that is any villages is connected to the others with a clear route at least).

    Unfortunately, we have only one team to rebuild the roads. Now,please tell us how long do you think these roads can be reconnected.

    Input

    The first line contains a number T denotes the number of test case.

    For each test case,

    In the first line, you will get two number N (1N1000) and M(1MN×N), denotes the number of towns and the number of roads.

    The next M lines, each contains three number A,B,C, denotes there is a road between A and B that needed C (1×C×1000) minutes to rebuild.

    Output

    For each test case, you should output a line contains a number denotes the minimal time need to rebuild the roads so that all the towns are connected.

    Sample input and output

    Sample InputSample Output
    2
    3 3
    1 2 3
    2 3 3
    3 1 7
    3 3
    1 2 3
    2 3 3
    3 1 1
    6
    4
    #include <iostream>
    #include <algorithm>
    using namespace std;
    
    int V,E,v[1005];
    class edge {
    public:
        int weight,from,to;
    }e[1000005];
    
    bool cmp(edge a,edge b) {
        return a.weight<b.weight;
    }
    
    int find(int x) {
        return (v[x]==x)?x:(v[x]=find(v[x]));
    }
    
    void MST() {
        int vnum=0,all_weight=0,x,y;
        for (int i=0; i<E&&vnum<V-1; i++) {
            x=find(e[i].from);
            y=find(e[i].to);
            if (x!=y) {
                v[x]=y;
                all_weight+=e[i].weight;
                vnum++;
            }
        }
        printf("%d
    ",all_weight);
    }
    
    int main() {
        int t;
        scanf("%d",&t);
        while (t--) {
            scanf("%d%d",&V,&E);
            for (int i=0; i<V; i++)
                v[i]=i;
            for (int i=0; i<E; i++) {
                scanf("%d%d%d",&e[i].from,&e[i].to,&e[i].weight);
                e[i].from--;
                e[i].to--;
            }
            sort(e, e+E, cmp);
            MST();
        }
    }
  • 相关阅读:
    ElasticSearch基本用法
    几款Http小服务器
    【最长上升子序列】HDU 1087——Super Jumping! Jumping! Jumping!
    方差与样本方差、协方差与样本协方差
    方差与样本方差、协方差与样本协方差
    统计推断(statistical inference)
    统计推断(statistical inference)
    R 语言学习(二)—— 向量
    R 语言学习(二)—— 向量
    R 语言的学习(一)
  • 原文地址:https://www.cnblogs.com/soildom/p/7979192.html
Copyright © 2011-2022 走看看