其他分享
首页 > 其他分享> > 图7 公路村村通

图7 公路村村通

作者:互联网

题目: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;
     } 

 



标签:node,right,struct,int,公路,MAX,村村通,left
来源: https://www.cnblogs.com/simon-chou/p/13620072.html