题目:https://pintia.cn/problem-sets/1268384564738605056/problems/1286606445168746496
题解:https://blog.csdn.net/whd526/article/details/50718811
代码:

    #include<stdio.h>
    #define MAX 1005
    struct node{
        int u;
        int v;
        int w;
    };
    int f[MAX];
    int count = 0, sum = 0;
    struct node e[3*MAX];
    void quicksort(int left,int right){
        if(left>right)
        return;
        int i = left;
        int j = right;
        struct node temp;
        while(i != j){
            while(e[j].w >= e[left].w && i<j)
                j--;
            while(e[i].w <= e[left].w && i<j )
                i++;
            if(i < j){
                temp = e[i];
                e[i] = e[j];
                e[j] = temp;
            }
        }
        temp = e[i];
        e[i] = e[left];
        e[left] = temp;
        quicksort(left, i-1);
        quicksort(i+1, right);
        return;
    }
    int getf(int v){
        if(f[v]==v)
        return v;
        else
        f[v] = getf(f[v]);
        return f[v]; 
    }
    int merge(int v,int u){
        int t1 = getf(v);
        int t2 = getf(u);
        if(t1 != t2){
            f[t2] = t1;
            return 1;
        }
        return 0;
    }
    int main()
    {
        int n,m;
        scanf("%d",&n);
        scanf("%d",&m);
        for(int i = 1; i <= m; ++i){
            scanf("%d %d %d", &e[i].u, &e[i].v, &e[i].w);
        }
        quicksort(1, m);
        for(int i = 1; i <= n; ++i){
            f[i]=i;
        }
        for(int i = 1; i <= m; ++i){
            if(merge(e[i].u,e[i].v)){
                count++;
                sum = sum + e[i].w;
            }
            if(count == n-1)
            break;
        }
        if(count != n-1)
            printf("-1\n");
        else
            printf("%d\n",sum);
        return 0;
     } 

 



 posted on 2020-09-05 22:27  邢涌芝  阅读(107)  评论(0编辑  收藏  举报