POJ 2823

单调队列来做,简单题了。维护一个最大的,一个最小的即可。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>

using namespace std;

#define N 1001000

int num[N];
int bigque[N],bhead,btail;
int smalque[N],shead,stail;
int ansb[N],anss[N],bt,st;

void addbig(int v){
	while(bhead<btail){
		if(v>bigque[btail-1])
		btail--;
		else break;
	}
	bigque[btail++]=v;
}

void addsmall(int v){
	while(shead<stail){
		if(v<smalque[stail-1])
		stail--;
		else break;
	}
	smalque[stail++]=v;
}

int main(){
	int n,k;
	while(scanf("%d%d",&n,&k)!=EOF){
		bhead=btail=shead=stail=bt=st=0;
		for(int i=1;i<=n;i++)
		scanf("%d",&num[i]);
		int i;
		for(i=1;i<=k&&i<=n;i++){
			addbig(num[i]);
			addsmall(num[i]);
		//	cout<<"YES"<<endl;
		}
		if(k>=n){
			printf("%d\n",ansb[bt]);
			printf("%d\n",anss[st]);
		}
		else{
			ansb[bt++]=bigque[bhead];
			anss[st++]=smalque[shead];
			for(;i<=n;i++){
				if(bigque[bhead]==num[i-k]){
					bhead++;
				}
				addbig(num[i]);
				if(smalque[shead]==num[i-k])
				shead++;
				addsmall(num[i]);
				ansb[bt++]=bigque[bhead];
				anss[st++]=smalque[shead];
			}
			printf("%d",anss[0]);
			for(int i=1;i<st;i++)
			printf(" %d",anss[i]);
			printf("\n");
			printf("%d",ansb[0]);
			for(int i=1;i<bt;i++)
			printf(" %d",ansb[i]);
			printf("\n");
		}
	}
	return 0;
}

  

posted @ 2014-12-06 17:04  chenjunjie1994  阅读(177)  评论(0编辑  收藏  举报