【堆】AcWing839. 模擬堆
阿新 • • 發佈:2022-05-21
AcWing839. 模擬堆
題解
#include <iostream> using namespace std; const int N = 1e5+10; //hp:堆中下標k,集合中下標為hp[k] //ph:集合中下標k,堆中下標ph[k] int p[N], h[N], hp[N], ph[N], cnt, sz; void heap_swap(int a, int b) { swap(ph[hp[a]], ph[hp[b]]); swap(hp[a], hp[b]); swap(h[a], h[b]); } void down(int u) { int t = u; if(u * 2 <= sz && h[u * 2] < h[t]) t = u * 2; if(u * 2 + 1 <= sz && h[u * 2 + 1] < h[t]) t = u * 2 + 1; if(u != t) { heap_swap(t, u); down(t); } } void up(int u) { while(u / 2 && h[u / 2] > h[u]) { heap_swap(u, u/2); u /= 2; } } int main() { int n, k, x; string c; scanf("%d",&n); while(n --) { cin >> c; if(c == "I") { scanf("%d", &k); h[++sz] = k; p[++cnt] = k; hp[sz] = cnt; ph[cnt] = sz; up(sz); } else if(c == "PM") printf("%d\n",h[1]); else if(c == "DM") { heap_swap(1, sz); sz -- ; down(1); } else if(c == "D") { scanf("%d",&k); k = ph[k]; heap_swap(k, sz); sz -- ; down(k); up(k); } else{ scanf("%d%d", &k, &x); h[ph[k]] = x; down(ph[k]); up(ph[k]); } } return 0; }