【模板】左偏树/可并堆
题目描述
如题,一开始有
1 x y:将第个数和第 个数所在的小根堆合并(若第 或第 个数已经被删除或第 和第 个数在同一个堆内,则无视此操作)。 2 x:输出第个数所在的堆最小数,并将这个最小数删除(若有多个最小数,优先删除先输入的;若第 个数已经被删除,则输出 并无视删除操作)。
输入格式
第一行包含两个正整数
第二行包含
接下来
操作 1 x y
操作 2 x
输出格式
输出包含若干行整数,分别依次对应每一个操作
样例 #1
样例输入 #1
5 5
1 5 4 2 3
1 1 5
1 2 5
2 2
1 4 2
2 2样例输出 #1
1
2提示
【数据规模】
对于
对于
对于 int 范围内。
【样例解释】
初始状态下,五个小根堆分别为:
第一次操作,将第
第二次操作,将第
第三次操作,将第
第四次操作,将第
第五次操作,将第
故输出依次为
性质
合并
c++
#include<iostream>
#include<vector>
#include<algorithm>
#include<queue>
#include<cstring>
#include<cmath>
#include<set>
#include<map>
using namespace std;
#define ll long long
#define ull unsigned long long
#define endl '\n'
const int N = 1e5 + 5;
const int mod = 1e9 + 7;
const ll inf = 1e18;
int dir[4][2] = {-1, 0, 0, 1, 1, 0, 0, -1};//上右下左
int a[N], lc[N], rc[N], dis[N], fa[N];
int find(int x) {
if (fa[x] == x) {
return x;
}
return fa[x] = find(fa[x]);
}
int merge(int x, int y) {
if (!x || !y) {//如果一个堆为空则返回另一个堆
return x + y;
}
if (a[x] == a[y]) {
if (x > y) {//题目要求 优先删除先输入的
swap(x, y);
}
} else {
if (a[x] > a[y]) {
swap(x, y);
}
}
rc[x] = merge(rc[x], y);// 合并右儿子与另一个堆,作为合并后的堆的右儿子
if (dis[lc[x]] < dis[rc[x]]) {//维护左偏的性质 左儿子的距离大于右儿子
swap(lc[x], rc[x]);
}
dis[x] = dis[rc[x]] + 1;//更新距离(性质)任何一个结点的距离等于右儿子的距离+1
return x;// 返回合并后的根
}
void solve() {
int n, m;
cin >> n >> m;
for (int i = 1; i <= n; i++) {
cin >> a[i];
fa[i] = i;// 初始化并查集
}
dis[0] = -1;// 空节点的dis为-1
while (m--) {
int op, x, y;
cin >> op;
if (op == 1) {// 合并堆
cin >> x >> y;
if (a[x] == -1 || a[y] == -1) {
continue;
}
x = find(x), y = find(y);
if (x != y) {
fa[x] = fa[y] = merge(x, y);
}
} else {// 删除堆顶
cin >> x;
if (a[x] == -1) {// 已经被删过了
cout << -1 << endl;
continue;
}
x = find(x);
cout << a[x] << endl;
a[x] = -1;
fa[lc[x]] = fa[rc[x]] = fa[x] = merge(lc[x], rc[x]);
}
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
int _ = 1;
//cin >> _;
while (_--)
solve();
return 0;
}