2025.11.06 力扣每日一题

3607.电网维护

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;
        }
    }
};

好难不太会写,找的题解做的详解,记得复习!!!

相关推荐
tryxr1 小时前
矩阵的几种基础变换
java·数据结构·算法·矩阵
mmmmath_31 小时前
LeetCode.028.找出字符串中第一个匹配项的
数据结构·算法·leetcode
Selvaggia1 小时前
DMD(Distribution Matching Distillation,分布匹配蒸馏)
算法
Navigator_Z1 小时前
LeetCode //C - 1255. Maximum Score Words Formed by Letters
c语言·算法·leetcode
All for pursuit.1 小时前
【栈-4】739.每日温度
数据结构·c++·算法·leetcode
开开心心就好2 小时前
安卓手写文字生成工具,多种纸张一直免费
网络·网络协议·tcp/ip·leetcode·智能手机·电脑·模拟退火算法
All for pursuit.2 小时前
【栈-5】84.柱状图中最大的矩形
数据结构·c++·算法·leetcode
wzdark2 小时前
数据压缩算法的时间复杂度与压缩率权衡4
算法
小陈phd2 小时前
深入理解agent学习笔记(一)——现代agent介绍
人工智能·算法
圣保罗的大教堂3 小时前
leetcode 1665. 完成所有任务的最少初始能量 中等
leetcode