http://acm.hust.edu.cn/vjudge/contest/view.action?cid=34121#problem/G
// File Name: g.cpp
// Author: bo_jwolf
// Created Time: 2013年10月17日 星期四 15:33:34
#include<vector>
#include<list>
#include<map>
#include<set>
#include<deque>
#include<stack>
#include<bitset>
#include<algorithm>
#include<functional>
#include<numeric>
#include<utility>
#include<sstream>
#include<iostream>
#include<iomanip>
#include<cstdio>
#include<cmath>
#include<cstdlib>
#include<cstring>
#include<ctime>
using namespace std;
const int maxn = 1000005;
int num[ maxn ];
int temp[ maxn ], dis[ maxn ];
int main(){
int n, m;
int *beg = temp, *end = temp;
while( scanf( "%d%d", &n, &m ) != EOF ){
for( int i = 0; i < n; ++i )
scanf( "%d", &num[ i ] );
for( int i = 0; i < n; ++i ){
end = lower_bound( beg, end, num[ i ] );
*end = num[ i ];
dis[ end - temp ] = i;
++end;
if( i - dis[ beg - temp ] >= m )
++beg;
if( i + 1 >= m )
printf( "%d ", *beg );
}
puts( "" );
beg = end = temp;
for( int i = 0; i < n; ++i ){
end = lower_bound( beg, end, num[ i ], greater< int >() );
*end = num[ i ];
dis[ end - temp ] = i;
++end;
if( i - dis[ beg - temp ] >= m )
++beg;
if( i + 1 >= m )
printf( "%d ", *beg );
}
}
return 0;
}