码迷,mamicode.com
首页 > 其他好文 > 详细

HDOJ 1879 Kruskal实现

时间:2017-11-20 19:04:08      阅读:108      评论:0      收藏:0      [点我收藏+]

标签:scan   efi   include   style   bsp   amp   sort   end   main   

#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实现

标签:scan   efi   include   style   bsp   amp   sort   end   main   

原文地址:http://www.cnblogs.com/neopolitan/p/7867302.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!