HDU2988 Dark roads(最小生成树kruskal)

Dark roads

题目链接:

http://acm.hdu.edu.cn/showproblem.php?pid=2988

解题思路:

kruskal求最小生成树之后,直接用总权值减去即可。

AC代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

const int maxn = 200010;
int ans,sum;
int pa[maxn];
int n,m;

struct Edge{
    int u,v,w;
}edge[maxn];

bool cmp(Edge a,Edge b){
    return a.w < b.w;
}

int Find(int x){
    if(pa[x] != x)
        pa[x] = Find(pa[x]);
    return pa[x];
}

int kruskal(){
    int u,v,cnt = n,l = 0;
    for(int i = 0; i < m; i++){
        u = Find(edge[i].u);
        v = Find(edge[i].v);
        if(u != v){
            l += edge[i].w;
            pa[v] = u;
            if(--cnt==1)
                break;
        }
    }
    return l;
}

int main(){
    while(scanf("%d%d",&n,&m),n+m){
        ans = 0;
        for(int i = 0; i < m; i++){
            scanf("%d%d%d",&edge[i].u,&edge[i].v,&edge[i].w);
            ans += edge[i].w;
        }
        for(int i = 0; i < m; i++)
            pa[i] = i;
        sort(edge,edge+m,cmp);
        sum = kruskal();
        printf("%d\n",ans-sum);
    }
    return 0;
}



你可能感兴趣的:(最小生成树,kruskal)