Description
Window position | Minimum value | Maximum value |
---|---|---|
[1 3 -1] -3 5 3 6 7 | -1 | 3 |
1 [3 -1 -3] 5 3 6 7 | -3 | 3 |
1 3 [-1 -3 5] 3 6 7 | -3 | 5 |
1 3 -1 [-3 5 3] 6 7 | -3 | 5 |
1 3 -1 -3 [5 3 6] 7 | 3 | 6 |
1 3 -1 -3 5 [3 6 7] | 3 | 7 |
Your task is to determine the maximum and minimum values in the sliding window at each position.
Input
Output
Sample Input
8 3 1 3 -1 -3 5 3 6 7
Sample Output
-1 -3 -3 -3 3 3 3 3 5 5 6 7
这题可以用单调队列搞 见我这篇
长记性记得g++超时
/*********** poj Sliding Window 2016.3.17 ***********/ #include <iostream> #include<cstdio> #include<cstring> using namespace std; struct Node { int l,r,minn,maxn; }num[4000000]; int cnt[1000000]; int min(int a,int b){if(a<b)return a;return b;} int max(int a,int b){if(a>b)return a;return b;} void build(int rt,int l,int r) { num[rt].l=l;num[rt].r=r; if(l==r) { num[rt].maxn=cnt[l]; num[rt].minn=cnt[l]; return; } int mid=(l+r)/2; build(rt<<1,l,mid); build(rt<<1|1,mid+1,r); num[rt].maxn=max(num[rt<<1].maxn,num[rt<<1|1].maxn); num[rt].minn=min(num[rt<<1].minn,num[rt<<1|1].minn); } int query1(int rt,int l,int r) { if(num[rt].l==l&&num[rt].r==r) return num[rt].minn; int mid=(num[rt].l+num[rt].r)/2; if(r<=mid) return query1(rt<<1,l,r); else if(l>mid) return query1(rt<<1|1,l,r); else return min(query1(rt<<1,l,mid),query1(rt<<1|1,mid+1,r)); } int query2(int rt,int l,int r) { if(num[rt].l==l&&num[rt].r==r) return num[rt].maxn; int mid=(num[rt].l+num[rt].r)/2; if(r<=mid) return query2(rt<<1,l,r); else if(l>mid) return query2(rt<<1|1,l,r); else return max(query2(rt<<1,l,mid),query2(rt<<1|1,mid+1,r)); } int main() { // freopen("cin.txt","r",stdin); int n,k; while(~scanf("%d%d",&n,&k)) { for(int i=1;i<=n;i++)scanf("%d",&cnt[i]); build(1,1,n); for(int i=1;i<=n-k;i++) printf("%d ",query1(1,i,i+k-1)); printf("%d\n",query1(1,n-k+1,n)); for(int i=1;i<=n-k;i++) printf("%d ",query2(1,i,i+k-1)); printf("%d\n",query2(1,n-k+1,n)); } return 0; }