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;
	}
};
相关推荐
码匠许师傅5 小时前
【C++ 面试真题】聊聊 C++ 中的 lambda 表达式
java·c++·面试
依然鸣5 小时前
PTA团体程序设计天梯赛L1真题讲解L1-085-088
数据结构·c++·经验分享·算法·深度优先·pat考试
沙盘客6 小时前
AFSIM 14篇 C++ 插件开发:扩展你的仿真能力
c++·后端
NeilYuen6 小时前
【vemory】高性能KV存储AOF方案设计
linux·c++·redis·缓存
王老师青少年编程8 小时前
2021年CSP-J初赛真题及答案解析(完善程序2)
c++·真题·csp-j·答案·csp·初赛·信奥赛
有点。8 小时前
C++二叉树(一)
开发语言·数据结构·c++
Lazionr8 小时前
stack与queue:底层实现与容器适配器
开发语言·数据结构·c++
豆沙沙包?9 小时前
C++~~~vector容器(p31-P40)
开发语言·c++
小小de风呀9 小时前
de风——【从零开始学习C++】(十八):AVL树——让二叉搜索树自己“站起来“的自平衡黑科技
c++·科技·学习
牛油果子哥q9 小时前
C++STL容器详解:vector/list/string底层扩容、迭代器失效终极解决、容器选型避坑
开发语言·c++·list