我luogu主页的代码模版

该代码示例展示了如何用C++实现Kruskal算法,通过并查集数据结构构建最小生成树的重构树。首先,定义了Edge和Node结构体,接着对边按权重排序,并利用findRoot和unionSets函数处理并查集。最终,输出Kruskal重构树的边。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

struct Edge {
    int u, v, weight;
};

struct Node {
    int parent, rank, size;
};

// 按照边权重从小到大排序
bool compareEdges(const Edge& a, const Edge& b) {
    return a.weight < b.weight;
}

// 查找节点的根节点
int findRoot(vector<Node>& nodes, int i) {
    if (nodes[i].parent != i) {
        nodes[i].parent = findRoot(nodes, nodes[i].parent);
    }
    return nodes[i].parent;
}

// 合并两个集合
void unionSets(vector<Node>& nodes, int xRoot, int yRoot) {
    if (nodes[xRoot].rank < nodes[yRoot].rank) {
        nodes[xRoot].parent = yRoot;
        nodes[yRoot].size += nodes[xRoot].size;
    } else if (nodes[xRoot].rank > nodes[yRoot].rank) {
        nodes[yRoot].parent = xRoot;
        nodes[xRoot].size += nodes[yRoot].size;
    } else {
        nodes[yRoot].parent = xRoot;
        nodes[xRoot].rank++;
        nodes[xRoot].size += nodes[yRoot].size;
    }
}

// 构建Kruskal重构树
vector<Edge> buildReconstructionTree(vector<Edge>& edges, int n) {
    vector<Node> nodes(n);
    for (int i = 0; i < n; i++) {
        nodes[i].parent = i;
        nodes[i].rank = 0;
        nodes[i].size = 1;
    }

    sort(edges.begin(), edges.end(), compareEdges);

    vector<Edge> result;
    for (const auto& edge : edges) {
        int xRoot = findRoot(nodes, edge.u);
        int yRoot = findRoot(nodes, edge.v);

        if (xRoot != yRoot) {
            result.push_back(edge);
            unionSets(nodes, xRoot, yRoot);
        }
    }

    return result;
}

int main() {
    int n = 6;
    vector<Edge> edges = {{0, 1, 4}, {0, 2, 2}, {1, 2, 1}, {2, 3, 5}, {3, 4, 3}, {3, 5, 2}, {4, 5, 1}};

    vector<Edge> reconstructionTree = buildReconstructionTree(edges, n);

    cout << "Edges in the Kruskal Reconstruction Tree:" << endl;
    for (const auto& edge : reconstructionTree) {
        cout << edge.u << " - " << edge.v << ", Weight: " << edge.weight << endl;
    }

    return 0;
}

Kruskal重构树

解释

在这个示例中,我们定义了一个边(Edge)结构体来表示图的边,以及一个节点(Node)结构体来表示Kruskal重构树中的节点,其中包含了节点的父节点、秩和大小。然后,我们使用Kruskal算法对边按权重进行排序,并使用并查集数据结构来构建Kruskal重构树。最后,我们输出Kruskal重构树中的边。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值