POJ1442:Black Box
阿新 • • 發佈:2019-01-18
題目 urn poj log name inline const cst -a
淺談堆:https://www.cnblogs.com/AKMer/p/10284629.html
題目傳送門:http://poj.org/problem?id=1442
用對頂堆維護第\(k\)小即可。保持小根堆大小逐漸遞增就行。
時間復雜度:\(O(mlogn)\)
空間復雜度:\(O(n)\)
代碼如下:
#include <cstdio> #include <algorithm> using namespace std; const int maxn=3e4+5; int n,m; int a[maxn],u[maxn]; int read() { int x=0,f=1;char ch=getchar(); for(;ch<'0'||ch>'9';ch=getchar())if(ch=='-')f=-1; for(;ch>='0'&&ch<='9';ch=getchar())x=x*10+ch-'0'; return x*f; } struct Heap { int tot; int tree[maxn]; void ins(int v) { tree[++tot]=v; int pos=tot; while(pos>1) { if(tree[pos]<tree[pos>>1]) swap(tree[pos],tree[pos>>1]),pos>>=1; else break; } } int pop() { int res=tree[1]; tree[1]=tree[tot--]; int pos=1,son=2; while(son<=tot) { if(son<tot&&tree[son|1]<tree[son])son|=1; if(tree[son]<tree[pos]) swap(tree[son],tree[pos]),pos=son,son=pos<<1; else break; } return res; } }T1,T2; int main() { n=read(),m=read(); for(int i=1;i<=n;i++) a[i]=read(); for(int i=1;i<=m;i++) u[i]=read(); sort(u+1,u+m+1); for(int i=1,st=1;i<=m;i++) { while(st<=u[i]) { if(a[st]>=T1.tree[1])T1.ins(a[st]); else T2.ins(-a[st]); st++; } while(T2.tot<i)T2.ins(-T1.pop()); while(T2.tot>i)T1.ins(-T2.pop()); printf("%d\n",-T2.tree[1]); } return 0; }
POJ1442:Black Box