【ACM】- HDU-1879 继续畅通工程 【最小生成树】

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_26398495/article/details/82692631
题目链接

题目分析

最小生成树问题;

解题思路

Kruskal算法 + 并查集即可;
思路(一):把修通道路(边)的权值(距离)令为0即可;
思路(二):对于修通的道路两端,输入后立即合并集合,不再加入边队列;


AC程序(C++)(思路一)
/**********************************
*@ID: 3stone
*@ACM: HDU-1879 继续畅通工程
*@Time: 18/9/13
*@IDE: VSCode + clang++ 
***********************************/
#include<cstdio >
#include<iostream>
#include<algorithm>
#include<queue>

using namespace std;
const int maxn = 110;

struct edge{
    int u, v, cost;
    edge() {}
    edge(int _u, int _v, int _cost) : u(_u), v(_v), cost(_cost) {} //构造函数,便于加入结点
    bool operator < (const edge& n) const { //规定优先级
        return cost > n.cost; //注意和sort函数是相反的
    }
};
int N, M;
int far[maxn]; //并查集

//寻根
int find_root(int a) {
    int root = a;
    while(root != far[root]) root = far[root];

    while(a != far[a]) { //路径压缩
        int cur = a;
        a = far[a];
        far[cur] = root;
    }
    return root;
}

//合并集合
void union_set(int a, int b) {
    int root_a = find_root(a);
    int root_b = find_root(b);
    if(a != b){
        far[root_b] = root_a;
    }
}

int kruskal(priority_queue<edge> E) {
    for(int i = 1; i <= N; i++) far[i] = i; //初始化并查集
    int ans = 0;//权值和
    int edge_num = 0; //已选择的边数
    int cnt = N; //连通块数

    for(int i = 0; i < M; i++) {
        edge e = E.top(); E.pop(); //get fisrt edge
        int root_u = find_root(e.u);
        int root_v = find_root(e.v);

        if(root_u != root_v) { //if not belong to same set
            union_set(root_u, root_v);
            edge_num++;
            cnt--; //连通块数-1
            ans += e.cost;
        }
        if(edge_num == N - 1) break;  //边数等于结点数-1
    }
    if(cnt != 1) return -1;//只剩一个连通块(edge_num != N - 1 也没问题)
    else return ans;

}//kruskal

int main() {
    int a, b, cost, status;
    while(scanf("%d", &N) != EOF) {
        if(N == 0) break;
        M = N * (N - 1) / 2;
        priority_queue<edge> E; //保存所有边(无clear()函数,每次重新定义时间最快)
                                //优先级和sort()函数是相反的
        for(int i = 0; i < M; i++) {
            scanf("%d %d %d %d", &a, &b, &cost, &status);
            if(status == 0) { //未修通
                E.push(edge(a, b, cost)); //加入堆
            } else { //已修通
                E.push(edge(a, b, 0)); //已修通,权值令为0
            }

        }

        printf("%d\n", kruskal(E)); //输出最小成本

    }//while

    system("pause");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_26398495/article/details/82692631