POJ2823
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
using namespace std;
#define ll long long
#define re register
const int N=1e6+10;
inline void read(int &a)
{
a=0;
int d=1;
char ch;
while(ch=getchar(),ch>'9'||ch<'0')
if(ch=='-')
d=-1;
a=ch^48;
while(ch=getchar(),ch>='0'&&ch<='9')
a=(a<<3)+(a<<1)+(ch^48);
a*=d;
}
inline void write(int x)
{
if(x<0)
putchar(45),x=-x;
if(x>9)
write(x/10);
putchar(x%10+'0');
}
struct note
{
int pos,val;
}qma[N],qmi[N];
int ma[N],mi[N],cnt=0;
int main()
{
int n,m;
while(~scanf("%d %d",&n,&m))
{
int l1,r1,l2,r2;
l1=r1=l2=r2=1;
cnt=0;
for(re int i=1;i<=m;i++)
{
int x;
read(x);
while(l1<r1&&qmi[r1-1].val>=x)
r1--;
qmi[r1].val=x;
qmi[r1++].pos=i;
while(l2<r2&&qma[r2-1].val<=x)
r2--;
qma[r2].val=x;
qma[r2++].pos=i;
}
for(re int i=m+1;i<=n;i++)
{
ma[++cnt]=qma[l2].val;
mi[cnt]=qmi[l1].val;
int x;
read(x);
while(l1<r1&&i-qmi[l1].pos>=m)
l1++;
while(l1<r1&&qmi[r1-1].val>=x)
r1--;
qmi[r1].val=x;
qmi[r1++].pos=i;
while(l2<r2&&i-qma[l2].pos>=m)
l2++;
while(l2<r2&&qma[r2-1].val<=x)
r2--;
qma[r2].val=x;
qma[r2++].pos=i;
}
ma[++cnt]=qma[l2].val;
mi[cnt]=qmi[l1].val;
for(re int i=1;i<cnt;i++)
write(mi[i]),putchar(' ');
write(mi[cnt]);putchar('
');
for(re int i=1;i<cnt;i++)
write(ma[i]),putchar(' ');
write(ma[cnt]),putchar('
');
}
return 0;
}