1. 程式人生 > >poj2823單調隊列

poj2823單調隊列

def assert math pre stream cas vector long long 技術

這個裸題,滑動窗口求最大最小值,單調隊列來兩邊,一次單調遞增q[s]就是最小值,一次單調遞減q[s]就是最大值

cin會超時,解除同步也沒用。。。

技術分享
#include<map>
#include<set>
#include<cmath>
#include<queue>
#include<stack>
#include<vector>
#include<cstdio>
#include<cassert>
#include<iomanip>
#include<cstdlib>
#include
<cstring> #include<iostream> #include<algorithm> #define pi acos(-1) #define ll long long #define mod 1000000007 #define ls l,m,rt<<1 #define rs m+1,r,rt<<1|1 #pragma comment(linker, "/STACK:1024000000,1024000000") using namespace std; const double g=10.0,eps=1e-9; const int N=1000000+10,maxn=500+100,inf=0x3f3f3f
; int a[N],q[N]; int minn[N],maxx[N]; int main() { /* ios::sync_with_stdio(false); cin.tie(0);*/ int n,k; while(~scanf("%d%d",&n,&k)){ for(int i=0;i<n;i++)scanf("%d",&a[i]); int s=0,t=0; for(int i=0;i<n;i++) { while(s<t&&a[i]>a[q[t-1
]])t--; q[t++]=i; if(s<t&&q[t-1]-q[s]>=k)s++; /* for(int j=s;j<t;j++)cout<<a[q[j]]<<" "; cout<<endl;*/ minn[i]=a[q[s]]; } s=0,t=0; for(int i=0;i<n;i++) { while(s<t&&a[i]<a[q[t-1]])t--; q[t++]=i; if(s<t&&q[t-1]-q[s]>=k)s++; /* for(int j=s;j<t;j++)cout<<a[q[j]]<<" "; cout<<endl;*/ maxx[i]=a[q[s]]; } for(int i=k-1;i<n;i++) printf("%d%c",maxx[i],i==n-1?\n: ); for(int i=k-1;i<n;i++) printf("%d%c",minn[i],i==n-1?\n: ); } return 0; }
View Code

poj2823單調隊列