C++ 并查集算法:高效解决账户合并问题

在处理账户合并问题时,并查集算法提供了一种高效的解决方案。本文将介绍如何使用 C++ 实现并查集算法,并通过代码示例演示其应用。

代码示例

以下是经过修正后的 C++ 代码,用于解决账户合并问题:

#include <iostream>
#include <vector>
#include <unordered_map>

using namespace std;

int find(vector<int>& parent, int x) {
    if (parent[x] == x) {
        return x;
    }
    return parent[x] = find(parent, parent[x]);
}

void unionSets(vector<int>& parent, int x, int y) {
    int rootX = find(parent, x);
    int rootY = find(parent, y);
    if (rootX != rootY) {
        parent[rootX] = rootY;
    }
}

int main() {
    int m, n;
    cin >> m >> n;

    vector<int> parent(n + 1);
    for (int i = 1; i <= n; i++) {
        parent[i] = i;
    }

    unordered_map<int, bool> accountSeen;
    for (int i = 0; i < m; i++) {
        int k;
        cin >> k;
        int firstAccount;
        cin >> firstAccount;
        accountSeen[firstAccount] = true;
        for (int j = 1; j < k; j++) {
            int account;
            cin >> account;
            accountSeen[account] = true;
            unionSets(parent, firstAccount, account);
        }
    }

    unordered_map<int, int> rootCount;
    for (int i = 1; i <= n; i++) {
        rootCount[find(parent, i)]++;
    }

    int minUsers = 0;
    for (auto it = rootCount.begin(); it != rootCount.end(); it++) {
        if (it->second > 0) {
            minUsers++;
        }
    }

    cout << minUsers << endl;

    return 0;
}

代码说明

  1. 并查集: 代码使用 parent 向量实现并查集,其中 parent[i] 表示元素 i 的父节点。
  2. 路径压缩: find 函数在查找根节点时使用了路径压缩优化,将查找路径上的所有节点直接指向根节点,提高效率。
  3. 按秩合并 (可选): 为了进一步优化,可以考虑在 unionSets 函数中实现按秩合并,将较小的树合并到较大的树下,降低树的高度。

总结

本文介绍了使用 C++ 并查集算法解决账户合并问题的解决方案。并查集算法提供了一种高效的方式来处理这类问题,并且代码实现相对简单。通过理解和应用并查集,您可以有效地解决各种实际问题。

C++ 并查集算法:高效解决账户合并问题

原文地址: https://www.cveoy.top/t/topic/rfn 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录