记得我刚学 那会儿, (苹果女皇)曾经用队列反向优化了小苹果,并提出了双端优先队列。
而我在大概建立 之前(也就是两年半前),我就想到了以下思路:
维护一个大根堆,维护一个小根堆,然后维护对应的位置即可。
但是一直懒得写,直到有一天 发了个动态说 priority_deque 可以用 multiset,我发现不对,因为 priority_deque 查询应该是 的,于是把代码写出来了。
这么简单的算法我还等了两年半才写,我太菜了
测试代码:
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
struct priority_deque{
LL h[100005],h2[100005];
int n=0,to12[100005],to21[100005];
void upmax(int u){
while ((u>1)&&(h[u]>h[u>>1])){swap(h[u],h[u>>1]);swap(to12[u],to12[u>>1]);swap(to21[to12[u]],to21[to12[u>>1]]);u>>=1;}
return;
}
void upmin(int u){
while ((u>1)&&(h2[u]<h2[u>>1])){swap(h2[u],h2[u>>1]);swap(to21[u],to21[u>>1]);swap(to12[to21[u]],to12[to21[u>>1]]);u>>=1;}
return;
}
void downmax(int u){
int v;
while ((v=(u<<1))<=n){
if (((v|1)<=n)&&(h[v|1]>h[v])){v|=1;}
if (h[v]<=h[u]){break;}
swap(to12[u],to12[v]);swap(to21[to12[u]],to21[to12[v]]);
swap(h[v],h[u]);u=v;
}
return;
}
void downmin(int u){
int v;
while ((v=(u<<1))<=n){
if (((v|1)<=n)&&(h2[v|1]<h2[v])){v|=1;}
if (h2[v]>=h2[u]){break;}
swap(to21[u],to21[v]);swap(to12[to21[u]],to12[to21[v]]);
swap(h2[v],h2[u]);u=v;
}
return;
}
void push(LL x){
++n;
h[n]=x;
h2[n]=x;
to12[n]=n;
to21[n]=n;
upmax(n);
upmin(n);
return;
}
LL topmax(){return h[1];}
LL topmin(){return h2[1];}
void popmax(){
if (n==1){--n;return;}
int tmp=to12[1];
swap(h[n],h[1]);
swap(to12[n],to12[1]);swap(to21[to12[n]],to21[to12[1]]);
swap(h2[n],h2[tmp]);
swap(to21[tmp],to21[n]);swap(to12[to21[tmp]],to12[to21[n]]);
--n;
downmax(1);
if (tmp<=n){upmin(tmp);downmin(tmp);}
return;
}
void popmin(){
if (n==1){--n;return;}
int tmp=to21[1];
swap(h2[n],h2[1]);
swap(to21[n],to21[1]);swap(to12[to21[n]],to12[to21[1]]);
swap(h[n],h[tmp]);
swap(to12[tmp],to12[n]);swap(to21[to12[tmp]],to21[to12[n]]);
--n;
downmin(1);
if (tmp<=n){upmax(tmp);downmax(tmp);}
return;
}
}lsy_apple_queen;
multiset<int> test;
void insert(int x){
if (lsy_apple_queen.n==100000){return;}
lsy_apple_queen.push(x);
test.insert(x);
return;
}
void query(){
if (lsy_apple_queen.n){
assert(lsy_apple_queen.topmax()==*test.rbegin());
assert(lsy_apple_queen.topmin()==*test.begin());
}
return;
}
void popmin(){
if (lsy_apple_queen.n){
lsy_apple_queen.popmin();
test.erase(test.begin());
}
return;
}
void popmax(){
if (lsy_apple_queen.n){
lsy_apple_queen.popmax();
test.erase(--test.end());
}
return;
}
random_device rd;
mt19937_64 g(rd());
int main(){
int x,y;
while (1){
x=(g()%3)+1;y=(g()%341799)-174399;
cerr<<x<<" "<<y<<endl;
if (x==1){insert(y);}else if (x==2){popmin();}else{popmax();}
cerr<<"gunmu\n";
query();
}
return 0;
}
时隔两年半,我成功实现 苹果女皇 的梦想!