POJ 2823 Sliding Window (单调队列)

#include<stdio.h>
#define MAX 1000002

int arraySize;
int winLen;
int array[MAX];
int monQue[MAX];//monotonous queue
int front;
int back;
int indexArray[MAX];

void enqueue(int minOrMax, int winEnd){
	//elements bigger/smaller than winEnd get out of the queue from the back if output min/max
	while (back >= front &&
		(minOrMax == -1 ? monQue[back] >= array[winEnd] : monQue[back] <= array[winEnd]) ){
			back--;
	}

	back++;
	monQue[back] = array[winEnd];
	indexArray[back] = winEnd;
}

void dequeue(int winEnd){
	// the front element in the queue is out of the windown
	while (indexArray[front] <= winEnd - winLen){
			front++;
	}	
}

/* if minOrMax = -1 output min ,or output max */
void outputMinOrMaxInWin(int minOrMax){
	front = 1; 
	back = 0;
	int winEnd;
	for (winEnd = 0; winEnd < arraySize; winEnd++){
		enqueue(minOrMax, winEnd);
		dequeue(winEnd);
		//output
		if(winEnd >= winLen - 1){
			printf("%d%c", monQue[front], winEnd == arraySize - 1 ? '\n' : ' ');
		}
	}
}

void input(){
	scanf("%d %d", &arraySize, &winLen);
	int index;
	for (index = 0; index < arraySize; index++){
		scanf("%d", &array[index]);
	}
}

int main(){	
	//freopen("input.txt", "r", stdin);
	input();	
	outputMinOrMaxInWin(-1);
	outputMinOrMaxInWin(1);
	return 0;

}


 

你可能感兴趣的:(window,poj,Sliding,单调队列,2823)