cpp
//核心思路是利用 并查集 管理电网的连通性,结合 有序集合维护每个电网中在线的电站,从而高效处理两种类型的查询"
const int N = 100010; // 题目最大电站数量
int p[N]; // 并查集的父节点数组,p[i]表示电站i的父节点
class Solution {
public:
// 主函数,处理所有查询
vector<int> processQueries(int c, vector<vector<int>>& connections,vector<vector<int>>& queries) {
// 遍历编号 1~c 的所有电站,将并查集数组 p[i] 设为
// i(自己是自己的父节点)。
for (int i = 1; i <= c; i++) {
p[i] = i; // 每个电站初始为独立电网
}
// 遍历 connections 中的每一条电缆 [u, v],调用 merge(u, v) 函数:
for (auto& edge : connections) { // 便利
int x = edge[0], y = edge[1];
merge(x, y); // 合并x和y所在的电网
}
// 键(key):电网的根节点(代表整个电网);
// 值(value):set<int>(自动按编号升序排序的集合),存储该电网中所有在线电站。
// 遍历 1~c
// 的所有电站,找到每个电站所在电网的根节点,将电站编号插入对应根节点的
// set 中(初始所有电站均在线)。
unordered_map<int, set<int>> online;
for (int i = 1; i <= c; i++) {
int root = find(i); // 找到电站i所在电网的根节点
online[root].insert(i); // 将i加入该电网的在线集合
}
vector<int> ans;//存储所有类型 1 查询的结果。
for (auto& query : queries) {//对 queries 中的每个查询 [type, x](x 为电站编号)
int x = query[1], rx = find(x);
if (query[0] == 1) {
if (online[rx].count(x)) {
ans.push_back(x);// x在线,自己处理
} else {
// x离线,找电网中最小在线电站
ans.push_back(online[rx].empty() ? -1 : *online[rx].begin());
}
} else {
online[rx].erase(x);// 从在线集合中删除x
}
}
return ans;//将存储所有类型 1 查询结果的 ans 数组返回
}
// 并查集的查找(带路径压缩)
int find(int x) {
return x == p[x] ? x : p[x] = find(p[x]);
// p[x]=find(p[x])实现了路径压缩
}
// 并查集的合并
void merge(int x, int y) {
int rx = find(x), ry = find(y);
if (rx != ry) {
p[rx] = ry;
}
}
};
好难不太会写,找的题解做的详解,记得复习!!!