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;
	}
};
相关推荐
杜子不疼.4 小时前
【C++ AI 大模型接入 SDK】 - DeepSeek 模型接入(上)
开发语言·c++·chatgpt
石山代码5 小时前
C++ 内存分区 堆区
java·开发语言·c++
张小姐的猫8 小时前
【Linux】多线程 —— 线程互斥
linux·运维·服务器·c++
做人求其滴10 小时前
面试经典 150 题 380 274
c++·算法·面试·职场和发展·力扣
见叶之秋10 小时前
C++基础入门指南
开发语言·c++
计算机安禾10 小时前
【c++面向对象编程】第42篇:模板特化与偏特化:为特定类型定制实现
开发语言·c++·算法
玖釉-10 小时前
C++ 中的循环语句详解:while、do...while、for、嵌套循环与循环控制
开发语言·c++·算法
欧米欧11 小时前
C++进阶数据结构之搜索二叉树
开发语言·数据结构·c++
青小莫11 小时前
C++之vector讲解
c++·stl
计算机安禾12 小时前
【c++面向对象编程】第41篇:函数模板与类模板:泛型编程的基石
开发语言·c++·算法