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

这篇文章将介绍如何使用 C++ 中的并查集算法来解决账户合并问题。

问题描述:

给定一组账户,每个账户包含一个或多个邮箱地址。如果两个账户共享至少一个相同的邮箱地址,则认为这两个账户属于同一个人,需要将它们合并成一个账户。目标是找到所有独立的账户以及每个账户包含的邮箱地址。

解决方案:

并查集是一种高效的数据结构,用于管理集合的合并和查找操作。我们可以利用并查集来解决账户合并问题。

代码实现:

以下是使用 C++ 实现的并查集算法解决账户合并问题的代码:cpp#include #include #include <unordered_map>

using namespace std;

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

void unionSets(vector& 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;        vector<int> accounts(k);        for (int j = 0; j < k; j++) {            cin >> accounts[j];            if (accountSeen.find(accounts[j]) != accountSeen.end()) {                unionSets(parent, accounts[j], accountSeen[accounts[j]]);            } else {                accountSeen[accounts[j]] = accounts[j];            }        }    }

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. find(parent, x) 函数用于查找元素 x 所属的集合,并进行路径压缩优化,将 x 的父节点直接指向根节点。2. unionSets(parent, x, y) 函数用于合并元素 xy 所属的集合。3. main() 函数首先读取输入数据,然后初始化并查集。4. 遍历每个账户,将属于同一账户的邮箱地址进行合并操作。5. 最后,统计根节点的数量,即为独立账户的数量。

示例:

输入:

5 32 1 23 2 3 44 4 5 1 2

输出:

4

结论:

使用并查集可以高效地解决账户合并问题。代码实现简单易懂,并且可以处理大规模的数据集。

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

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

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