http://poj.org/problem?id=2823
Test instructions
Gives the size of the array and the sliding window, each time the maximum and minimum values in the sliding window are output.
Ideas:
This problem can be regarded as a monotonous queue template problem, respectively, maintain a monotonous increment and monotonically decreasing queue, team tail in each insert maintenance can, team head maintenance is when the team first element is not within the scope of sliding window.
1#include <iostream>2#include <algorithm>3#include <cstring>4#include <cstdio>5#include <vector>6#include <stack>7#include <queue>8#include <cmath>9#include <map>Ten#include <Set> One using namespacestd; AtypedefLong Longll; -typedef pair<int,int>PLL; - Const intINF =0x3f3f3f3f; the Const intMAXN = 1e6+5; - - intN, K; - intA[MAXN]; + intQ[MAXN]; - intP[MAXN]; + A voidget_min () at { - intfrt=1, rear=1; - for(intI=1; i<k;i++) - { - while(Frt<=rear && q[rear]>=a[i]) rear--; -q[++rear]=A[i]; inp[rear]=i; - } to for(inti=k;i<=n;i++) + { - while(Frt<=rear && q[rear]>=a[i]) rear--; theq[++rear]=A[i]; *p[rear]=i; $ while(p[frt]<i-k+1) frt++;Panax Notoginsengprintf"%d%c", Q[frt],i==n?'\ n':' '); - } the } + A voidGet_max () the { + intfrt=1, rear=1; - for(intI=1; i<k;i++) $ { $ while(Frt<=rear && q[rear]<=a[i]) rear--; -q[++rear]=A[i]; -p[rear]=i; the } - for(inti=k;i<=n;i++)Wuyi { the while(Frt<=rear && q[rear]<=a[i]) rear--; -q[++rear]=A[i]; Wup[rear]=i; - while(p[frt]<i-k+1) frt++; Aboutprintf"%d%c", Q[frt],i==n?'\ n':' '); $ } - } - - intMain () A { + //freopen ("In.txt", "R", stdin); the while(~SCANF ("%d%d",&n,&k)) - { $ for(intI=1; i<=n;i++) scanf ("%d",&a[i]); the get_min (); the Get_max (); the } the return 0; -}
POJ 2823 Sliding Window (monotonic queue)