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;
	}
};
相关推荐
云栖梦泽21 分钟前
Linux内核与驱动:14.SPI子系统
linux·运维·服务器·c++
Gary Studio29 分钟前
安卓HAL C++基础-智能指针
开发语言·c++
还是阿落呀39 分钟前
基本控制结构2
c++
多思考少编码1 小时前
PAT甲级真题1001 - 1005题详细题解(C++)(个人题解)
c++·python·最短路·pat·算法竞赛
极客智造2 小时前
C++ 标准 IO 流全详解:cin /cout/get /getline 原理、用法、区别与避坑
c++·io
charlie1145141912 小时前
嵌入式C++工程实践第20篇:GPIO 输入模式内部电路 —— 芯片是如何“听“到外部信号的
开发语言·c++·stm32·单片机
样例过了就是过了4 小时前
LeetCode热题100 分割等和子集
数据结构·c++·算法·leetcode·动态规划
麦兜和小可的舅舅5 小时前
ClickHouse 列管理机制解析:从 COW、IColumn 到 CRTP
c++·clickhouse
旖-旎5 小时前
深搜练习(组合)(5)
c++·算法·深度优先·力扣
vegetablesssss5 小时前
vtk镜像图
c++·qt·vtk