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;
	}
};
相关推荐
不想写代码的星星3 小时前
std::function 详解:用法、原理与现代 C++ 最佳实践
c++
樱木Plus2 天前
深拷贝(Deep Copy)和浅拷贝(Shallow Copy)
c++
blasit4 天前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
肆忆_5 天前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星5 天前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛7 天前
delete又未完全delete
c++
端平入洛8 天前
auto有时不auto
c++
哇哈哈20219 天前
信号量和信号
linux·c++
多恩Stone9 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
蜡笔小马9 天前
21.Boost.Geometry disjoint、distance、envelope、equals、expand和for_each算法接口详解
c++·算法·boost