Sicily 7766:Dark roads(最小生成树)

Posted Vincent_Bryan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Sicily 7766:Dark roads(最小生成树)相关的知识,希望对你有一定的参考价值。

#include<bits/stdc++.h>
using namespace std;

struct Vertex{
    int start, end;
    int weight;
};
Vertex arr[200010];
int par[200010];
int n, m;
long long cost = 0;
int find(int n){
    while(par[n] != n){
        n = par[n];
    }
    return n;
}
void merge(int n1, int n2){
    while(par[n1] != n1){
        n1 = par[n1];
        par[n1] = n2;
    }
    par[n1] = n2;
}
bool cmp(Vertex v1, Vertex v2){
    return v1.weight < v2.weight;
}
long long func(){
    int ans = 0;
    sort(arr, arr+m, cmp);
    int i = 0;
    int k = 0;
    while(k < m){
        Vertex tmp = arr[k++];

        int n1 = find(tmp.start);
        int n2 = find(tmp.end);
        if(n1 == n2){
            continue;
        }
        else{
            cost += tmp.weight;
            if(n1 > n2)swap(n1, n2);
            merge(n2, n1);
            i++;
        }
    }

    return cost;
}

void init(int n, int m){
    for(int i = 0; i <= n; i++)par[i] = i;
    cost = 0;
    for(int i = 0; i <= m; i++){
        arr[i].start = arr[i].end = arr[i].weight = 0;
    }
}

int main(){
    while(scanf("%d%d", &n, &m) && n && m){
        long long total = 0;
        init(n, m);
        for(int i = 0; i < m; i++){
            scanf("%d%d%d", &arr[i].start, &arr[i].end, &arr[i].weight);
            total += arr[i].weight;
        }
        printf("%lld\\n", total-func());
    }
} 


/*
4 5
0 1 4
1 3 5
3 2 1
0 2 2 
0 3 7
7 11
0 1 7
0 3 5
1 2 8
1 3 9
1 4 7
2 4 5
3 4 15
3 5 6
4 5 8
4 6 9
5 6 11
*/                   

 

以上是关于Sicily 7766:Dark roads(最小生成树)的主要内容,如果未能解决你的问题,请参考以下文章

谁有the dark ride歌词啊?

HDU-1102 Constructing Roads ( 最小生成树 )

Constructing Roads(最小生成树)

Jungle Roads//最小生成树kruskal

HDU--1301--Jungle Roads(最小生成树)

hdu1301 Jungle Roads 最小生成树