HDOJ 1879 Kruskal实现

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HDOJ 1879 Kruskal实现相关的知识,希望对你有一定的参考价值。

#include <cstdio>
#include <algorithm>

using namespace std;

#define N 100

int parent[N];

struct road{
    int begin;
    int end;
    int value;
};

bool cmp(road a, road b){
    return a.value < b.value;
}

int find(int a){
    int begin = a;
    while (1)
        if (a == parent[a]){
            while (parent[begin] != a){
                int temp = begin;
                parent[begin] = a;
                begin = parent[temp];
            }
            break;
        }
        else
            a = parent[a];
    return a;
}

int main(){
    int n;
    while (scanf("%d", &n), n != 0){
        int temp = n * (n - 1) / 2;
        int count = 0;
        int total_value = 0;
        road roads[temp];
        for (int i = 0; i < n; i++)
            parent[i] = i;
        for (int i = 0; i < temp; i++){
            int built;
            scanf("%d %d %d %d", &roads[i].begin, &roads[i].end, &roads[i].value, &built);
            roads[i].begin -= 1;
            roads[i].end -= 1;
            if (built)
                roads[i].value = 0;
        }
        sort(roads, roads + temp, cmp);
        for (int i = 0; i < temp; i++){
            int parent_a = find(roads[i].begin);
            int parent_b = find(roads[i].end);
            if (parent_a != parent_b){
                count += 1;
                total_value += roads[i].value;
                parent[parent_b] = parent_a;
            }
            if (count == n - 1)
                break;
        }
        printf("%d\n", total_value);
    }
    return 0;
}

 

以上是关于HDOJ 1879 Kruskal实现的主要内容,如果未能解决你的问题,请参考以下文章

HDOJ 1879 Prim实现

hdoj1233 还是畅通工程(Prime || Kruskal)

HDOJ 1301最小生成树的Kruskal算法

HDU 1879 继续畅通工程

最小生成树算法

hdoj1102 Constructing Roads(Prime || Kruskal)