注意初始化,最开始的时候队列里应该放num【1】,如果不放的话,会与队列里的第一个比较,这样就不对了
AC代码如下:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int num[1110000];
int q[1110000], pos[1110000], head, tail;
int N, K;
void getmin(){
head = tail = 0;
q[0] = num[1];
pos[0] = 1;
for( int i = 2; i < K + 1; i++ ){
while( head <= tail && num[i] < q[tail] ) tail--;
tail++;
q[tail] = num[i];
pos[tail] = i;
}
printf( "%d", q[head] );
for( int i = K + 1; i <= N; i++ ){
while( head <= tail && num[i] < q[tail] ) tail--;
tail++;
q[tail] = num[i];
pos[tail] = i;
while( head <= tail && pos[head] < i - K + 1 ) head++;
printf( " %d", q[head] );
}
}
void getmax(){
head = tail = 0;
q[0] = num[1];
pos[0] = 1;
for( int i = 2; i < K + 1; i++ ){
while( head <= tail && num[i] > q[tail] ) tail--;
tail++;
q[tail] = num[i];
pos[tail] = i;
}
printf( "%d", q[head] );
for( int i = K + 1; i <= N; i++ ){
while( head <= tail && num[i] > q[tail] ) tail--;
tail++;
q[tail] = num[i];
pos[tail] = i;
while( head <= tail && pos[head] < i - K + 1 ) head++;
printf( " %d", q[head] );
}
}
int main(){
while( scanf( "%d%d", &N, &K ) != EOF ){
for( int i = 1; i <= N; i++ ){
scanf( "%d", &num[i] );
}
if( K > N ){
K = N;
}
getmin();
cout << endl;
getmax();
cout << endl;
}
return 0;
}