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;
	}
};
相关推荐
mit6.8243 小时前
一些C++的学习资料备忘
开发语言·c++
上去我就QWER3 小时前
深入解析Qt中的QDrag:实现灵活的拖放交互
c++·qt
ALex_zry4 小时前
深入解析gRPC C++动态反射:实现Proto消息的智能字段映射
开发语言·c++
沙威玛_LHE4 小时前
C++ 头文件:语言功能的 “模块化工具箱”(第三章)
c++
liu****4 小时前
12.线程同步和生产消费模型
linux·服务器·开发语言·c++·1024程序员节
顺顺 尼4 小时前
了解和使用多态
c++
0x00074 小时前
翻译《The Old New Thing》- 为什么 SHFormatDateTime 要接收一个未对齐的 FILETIME?
c++·windows
Pointer Pursuit5 小时前
C++——二叉搜索树
开发语言·c++
澪吟5 小时前
C++ 从入门到进阶:核心知识与学习指南
开发语言·c++