3607. 电网维护

3607. 电网维护


题目链接:3607. 电网维护

代码如下:

cpp 复制代码
class Solution {
public:
	vector<int> processQueries(int c, vector<vector<int>>& connections, vector<vector<int>>& queries) {
		vector<vector<int>> g(c + 1);
		for (auto& e : connections) {
			int x = e[0], y = e[1];
			g[x].push_back(y);
			g[y].push_back(x);
		}

		vector<int> belong(c + 1, -1);//记录每个节点所属的连通块
		vector<priority_queue<int, vector<int>, greater<>>> heaps;
		priority_queue<int, vector<int>, greater<>> pq;

		auto dfs = [&](auto&& dfs, int x)->void {
			belong[x] = heaps.size();//记录节点x在哪个堆
			pq.push(x);
			for (int y : g[x]) {
				if (belong[y] < 0) {
					dfs(dfs,y);
				}
			}
		};

		for (int i = 1;i <= c;i++) {
			if (belong[i] < 0) {
				dfs(dfs, i);
				heaps.push_back(move(pq));
			}
		}

		vector<int> res;
		vector<int8_t> offline(c + 1);
		for (auto& q : queries) {
			int x = q[1];
			if (q[0] == 2) {
				offline[x] = true;
				continue;
			}
			if(!offline[x]) {
				res.push_back(x);
				continue;
			}
			auto& h = heaps[belong[x]];
			//懒删除:取堆顶的时候,如果离线,才删除
			while(!h.empty()&&offline[h.top()]) {
				h.pop();
			}
			res.push_back(h.empty() ? -1 : h.top());
		}
		return res;
	}
};
相关推荐
J ..7 分钟前
C++ 多线程编程基础与 std::thread 使用
c++
你的冰西瓜7 分钟前
C++标准模板库(STL)全面解析
开发语言·c++·stl
闻缺陷则喜何志丹26 分钟前
【计算几何】仿射变换与齐次矩阵
c++·数学·算法·矩阵·计算几何
chen_ever29 分钟前
Protobuf详解(从安装到实战)
c++·rpc·信息与通信
hmbbcsm1 小时前
python做题小记(八)
开发语言·c++·算法
再睡一夏就好1 小时前
深入Linux线程:从轻量级进程到双TCB架构
linux·运维·服务器·c++·学习·架构·线程
特立独行的猫a2 小时前
C++开发中的Pimpl机制与类声明机制深度解析:现代C++的编译解耦艺术
开发语言·c++·pimpl
GoWjw2 小时前
在C&C++指针的惯用方法
c语言·开发语言·c++
君义_noip2 小时前
信息学奥赛一本通 1453:移动玩具 | 洛谷 P4289 [HAOI2008] 移动玩具
c++·算法·信息学奥赛·csp-s
superman超哥2 小时前
仓颉语言中错误恢复策略的深度剖析与工程实践
c语言·开发语言·c++·python·仓颉