poj2823 单调队列

一年前用treap死活搞不出,现在用单调队列直接水过!

//poj2823 //维护两个单调队列 //单调队列队头最大或最小,值和值的序号都要单调! #include <iostream> #include <queue> using namespace std; struct data { int x,id; }q1[1000010],q2[1000010]; int ans1[1000010],ans2[1000010],a[1000010],n,k,i; int head1,tail1,head2,tail2; void insert1(int x,int id) { if (head1==tail1+1) { q1[head1].x=x; q1[head1].id=id; tail1++; } else { while (q1[tail1].x>x && head1<=tail1) tail1--; tail1++; q1[tail1].x=x; q1[tail1].id=id; } } void insert2(int x,int id) { if (head2==tail2+1) { q2[head2].x=x; q2[head2].id=id; tail2++; } else { while (q2[tail2].x<x && head2<=tail2) tail2--; tail2++; q2[tail2].x=x; q2[tail2].id=id; } } int main() { cin >> n >> k; for (i=1;i<=n;i++) scanf("%d",&a[i]); head1=1;tail1=0; head2=1;tail2=0; for (i=1;i<=k;i++) { insert1(a[i],i); insert2(a[i],i); } ans1[1]=q1[1].x; ans2[1]=q2[1].x; for (i=1;i<=n-k;i++) { if (q1[head1].id==i) head1++; if (q2[head2].id==i) head2++; insert1(a[i+k],i+k); insert2(a[i+k],i+k); ans1[i+1]=q1[head1].x; ans2[i+1]=q2[head2].x; } for (i=1;i<n-k+1;i++) printf("%d ",ans1[i]); printf("%d/n",ans1[n-k+1]); for (i=1;i<n-k+1;i++) printf("%d ",ans2[i]); printf("%d/n",ans2[n-k+1]); //system("pause"); return 0; }

你可能感兴趣的:(insert,iostream)