kedaOJ#P0776. 【模板】可並堆

mcr130102發表於2024-07-14

思路

可並堆不會的看作者的 https://www.cnblogs.com/mcr130102/p/18301571

程式碼

複製都執行不了好吧

 #include <iostream>
 #include <vector>
 #include <queue>//堆用佇列實現
 #include <algorithm>
using namespace std;
const int MAXN = 1e5 + 5;
int parent[MAXN];
int find(int x) {
	if (parent[x] != x) parent[x] = find(parent[x]);
	return parent[x];
}   
void unionSet(int x, int y) {
	int px = find(x), py = find(y);
	if (px != py) parent[px] = py;
}
struct Node    {//使用結構體構建堆
	int val, dist, id;
	Node *left, *right;   
	Node(int v, int i) : val(v), dist(0), id(i), left(nullptr), right(nullptr) {}
};
Node* merge(Node* a, Node* b) {//合併堆
	if (!a) return b;
	if (!b) return a;
	if (a->val > b->val || (a->val == b->val && a->id > b->id)) swap(a, b);
	a->right = merge(a->right, b);
	if (!a->left || a->left->dist < a->right->dist) swap(a->left, a->right);
	a->dist = a->right ? a->right->dist + 1 : 0;
	return a;
}   
Node* pop(Node* a) {//將節點彈出堆
	Node* ret = merge(a->left, a->right);
	delete a;
	return ret;
}
Node* heap[MAXN];
bool deleted[MAXN];
int main() {
	int n, m;
	cin >> n >> m;
	vector<int> values(n + 1);
	for (int i = 1; i <= n; ++i) {
		cin >> values[i];
		parent[i] = i;
		heap[i] = new Node(values[i], i);
	}
	while (m--) {
		int op, x, y;
		cin >> op;
		if (op == 1) {
			cin >> x >> y;
			if (deleted[x] || deleted[y] || find(x) == find(y)) continue;
			int px = find(x), py = find(y);
			unionSet(px, py);
			heap[py] = merge(heap[px], heap[py]);
		} else if (op == 2) {
			cin >> x;
			if (deleted[x]) {
				cout << -1 << endl;
				continue;
			}
			int px = find(x);
			cout << heap[px]->val << endl;
			deleted[heap[px]->id] = true;
			heap[px] = pop(heap[px]);
		}
	}
	return 0;
}

相關文章