• 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
    ", total_value);
        }
        return 0;
    }
  • 相关阅读:
    第十四周总结
    《走出软件作坊》读后感
    航空公司信息可视化
    周总结
    REDIS实验
    第二阶段个人总结07
    第二阶段个人总结06
    第二阶段个人总结05
    第二阶段个人总结04
    第二阶段个人总结03
  • 原文地址:https://www.cnblogs.com/neopolitan/p/7867302.html
Copyright © 2020-2023  润新知