POJ 2823 Sliding Window

很CHUO的代码

用的是单调队列

还有更好的做法 以后补上

  
    
#include < stdio.h >

struct Queue{
int idx, val;
}que[
1000000 ];
int a[ 1000000 ];
int head, tail;

int main(){
int n, k;
scanf(
" %d%d " , & n, & k);
for ( int i = 0 ; i < n; ++ i){
scanf(
" %d " , & a[i]);
}
// k 为1时候的特殊情况, 还有更好的做法..
if ( k == 1 ){
for ( int i = 0 ; i < n; ++ i){
if ( i )
printf(
" " );
printf(
" %d " ,a[i]);
}
printf(
" \n " );
for ( int i = 0 ; i < n; ++ i){
if ( i )
printf(
" " );
printf(
" %d " ,a[i]);
}
printf(
" \n " );
return 0 ;
}
head
= tail = 0 ;
que[tail].val
= a[ 0 ];
que[tail].idx
= 0 ;
bool first = true ;
for ( int i = 1 ; i < n; ++ i){

while ( head <= tail && que[tail].val > a[i] ){
tail
-- ;
}
tail
++ ;
que[tail].val
= a[i];
que[tail].idx
= i;
while ( i - que[head].idx >= k ){
head
++ ;
}
if ( i >= k - 1 ){
if ( first )
first
= false ;
else
printf(
" " );
printf(
" %d " ,que[head].val);
}
}
printf(
" \n " );
head
= tail = 0 ;
que[tail].val
= a[ 0 ];
que[tail].idx
= 0 ;
first
= true ;
for ( int i = 1 ; i < n; ++ i){

while ( head <= tail && que[tail].val < a[i] ){
tail
-- ;
}
tail
++ ;
que[tail].val
= a[i];
que[tail].idx
= i;
if ( i - que[head].idx >= k ){
head
++ ;
}
if ( i >= k - 1 ){
if ( first )
first
= false ;
else
printf(
" " );
printf(
" %d " ,que[head].val);
}

}
printf(
" \n " );
return 0 ;
}

你可能感兴趣的:(window)