例题链接:Acwing 模拟堆
维护一个集合,初始时集合为空,支持如下几种操作:
I x,插入一个数 x;
PM,输出当前集合中的最小值;
DM,删除当前集合中的最小值(数据保证此时的最小值唯一);
D k,删除第 k 个插入的数;
C k x,修改第 k 个插入的数,将其变为 x;
现在要进行 N 次操作,对于所有第 2 个操作,输出当前集合的最小值。
输入格式
第一行包含整数 N。
接下来 N 行,每行包含一个操作指令,操作指令为 I x,PM,DM,D k 或 C k x 中的一种。
输出格式
对于每个输出指令 PM,输出一个结果,表示当前集合中的最小值。
每个结果占一行。
数据范围
1≤N≤1e5
−1e9≤x≤1e9
数据保证合法。
输入样例:
8
I -10
PM
I -10
D 1
C 2 8
I 6
PM
DM
输出样例:
-10
6
分析:由于多加了中间删除修改操作导致STL无法满足要求,于是手写堆用数组模拟实现。
正确代码
//#pragma GCC optimize(2)
#include<iostream>
#include<iomanip>
#include<cstdio>
#include<string>
#include<algorithm>
#include<cmath>
#include<queue>
#include<vector>
#include<map>
#include<stack>
#include<set>
#include<bitset>
#include<ctime>
#include<cstring>
#include<list>
#define ll long long
#define ull unsigned long long
#define INF 0x3f3f3f3f
#define mem(a,b) memset(a,b,sizeof(a))
using namespace std;
typedef pair<int, int> PII;
const int N = 1e6 + 7;
int heap[N], hp[N], ph[N],siz = 0,cnt=0;//hp[i]=k:编号为i是第k个插入的 ph[x]=y:第x个插入的编号为y ph[hp[i]]=i:第i个点的编号为j
int n;
void swa(int a, int b) //交换编号a b
{
swap(heap[a], heap[b]);
swap(hp[a], hp[b]);
swap(ph[hp[a]], ph[hp[b]]);
}
void down(int x) //下沉操作
{
int t = x;
if (2 * x <= siz && heap[t] > heap[2 * x])t = 2 * x;
if (2 * x +1<= siz && heap[t] > heap[2 * x+1])t = 2 * x+1;
if (t != x)
{
swa(x, t);
down(t);
}
}
void up(int x) //上浮起来操作
{
int t = x;
if ( t/2 >=1 && heap[t] < heap[t / 2])
{
t = t / 2;
swa(x, t);
up(t);
}
}
void solve()
{
cin >> n;
while (n--)
{
string s;
cin >> s;
if (s == "I") //末尾添加,然后上浮
{
int x;
cin >> x;
heap[++siz] = x;
hp[siz] = ++cnt;
ph[cnt] = siz;
up(siz);
}
if (s == "PM") //输出堆首
{
cout << heap[1] << endl;
}
if (s == "DM") //尾到首,尾指针前移,下沉删除
{
swa(1, siz);
siz--;
down(1);
}
if (s == "D") //堆尾换到k,尾指针前移,上浮下沉
{
int k;
cin >> k;
int u = ph[k]; //必须要用u来保存,否则会出错
swa(u, siz);
siz--;
down(u);
up(u);
}
if (s == "C") //直接修改,上浮下沉
{
int k, x;
cin >> k >> x;
heap[ph[k]] = x;
down(ph[k]);
up(ph[k]);
}
}
}
int main()
{
std::ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
solve();
return 0;
}
作者:Avalon Demerzel,喜欢我的博客就点个赞吧,更多图论与数据结构知识点请见作者专栏《图论与数据结构》