思路
可并堆不会的看作者的 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;
}
标签:kedaOJ,Node,right,P0776,val,int,px,find,模板
From: https://www.cnblogs.com/mcr130102/p/18301582