【BZOJ2096】[POI2010] Pilots
堆
#include<bits/stdc++.h> using namespace std; const int maxn = 3e6+5; int k,n,ans = 1,a[maxn]; struct data { int pos,val; data(int a,int b):pos(a),val(b){} }; bool operator<(data a,data b) {return a.val < b.val;} priority_queue<data> q1,q2; int read(){ int x=0,f=1;char ch=getchar(); while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();} while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();} return x*f; } void work(){ int t(1); for(int i = 1;i <= n; ++i){ q1.push(data(i,a[i])); q2.push(data(i,-a[i])); while(q1.top().val+q2.top().val>k){ t++; while(!q1.empty() && q1.top().pos < t) q1.pop(); while(!q2.empty() && q2.top().pos < t) q2.pop(); } ans = max(ans,i-t+1); } } int main(){
// freopen("pil.in","r",stdin);
// freopen("pil.out","w",stdout); k = read(),n = read(); for(int i = 1;i <= n; ++i) a[i] = read(); work(); printf("%d",ans); return 0; }
单调队列(手写)
#include<bits/stdc++.h> using namespace std; const int maxn = 3e6+5; int a[maxn],q1[maxn],q2[maxn]; int k,n,ans = 1; int read(){ int x=0,f=1;char ch=getchar(); while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();} while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();} return x*f; } void work(){ int l1(1),l2(1),r1(0),r2(0),t(1); for(int i = 1;i <= n; ++i){ while(l1<=r1 && a[i] >= a[q1[r1]]) r1--; while(l2<=r2 && a[i] <= a[q2[r2]]) r2--; q1[++r1] = i,q2[++r2] = i; while(a[q1[l1]]-a[q2[l2]] > k) if(q1[l1]<q2[l2]) t = q1[l1]+1,l1++; else t = q2[l2]+1,l2++; ans = max(ans,i-t+1); } } int main(){ // freopen("pil.in","r",stdin); // freopen("pil.out","w",stdout); k = read(),n = read(); for(int i = 1;i <= n; ++i) a[i] = read(); work(); printf("%d",ans); return 0; }
双端队列
#include<bits/stdc++.h> using namespace std; const int maxn = 3e6+5; int k,n,ans=0; int a[maxn]; int read(){ int x=0,f=1;char ch=getchar(); while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();} while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();} return x*f; } deque<int> q1; deque<int> q2; void work(){ int t; for(int i=1;i<=n;i++){ while((!q1.empty())&&a[q1.front()]<=a[i]) q1.pop_back();//单减 while((!q2.empty())&&a[q2.front()]>=a[i]) q2.pop_back();//单增 q1.push_back(i); q2.push_back(i); while( a[q1.front()] - a[q2.front()] > k ){ if(q2.front()>q1.front()) t=q1.front(),q1.pop_front(); else t=q2.front(),q2.pop_front(); } ans = max(ans,i-t); } } int main(){ // freopen("pil.in","r",stdin); // freopen("pil.out","w",stdout); k = read(),n = read(); for(int i = 1;i <= n; ++i) a[i] = read(); work(); printf("%d\n",ans); return 0; }
G102的孤儿们都要好好的啊。