【BZOJ】【P2096】【Poi2010】【Pilots】【题解】【二分+单调队列】

传送门:http://www.lydsy.com/JudgeOnline/problem.php?id=2096

答案满足二分性质……二分+判定

nlogn好像很慢……

Code:

#include<bits/stdc++.h>
using namespace std;
const int maxn=3e6+5;
int k,n;
int a[maxn];
deque<int>Min,Max;
int main(){
	scanf("%d%d",&k,&n);
	for(int i=1;i<=n;i++)scanf("%d",&a[i]);
	int l=1,r=n+1;
	while(l<r){
		int mid=(l+r)>>1,ok=0;
		Min.clear();Max.clear();
		for(int i=1;i<=mid;i++){
			while(Max.size()&&a[Max.back()]<=a[i])Max.pop_back();
			while(Min.size()&&a[Min.back()]>=a[i])Min.pop_back();
			Max.push_back(i);Min.push_back(i);
		}if(a[Max.front()]-a[Min.front()]<=k){l=mid+1;ok=1;continue;}	
		for(int i=1;i+mid<=n;i++){
			while(Max.size()&&Max.front()<=i)Max.pop_front();
			while(Min.size()&&Min.front()<=i)Min.pop_front();
			while(Max.size()&&a[Max.back()]<=a[i+mid])Max.pop_back();
			while(Min.size()&&a[Min.back()]>=a[i+mid])Min.pop_back();
			Max.push_back(i+mid);Min.push_back(i+mid);
			if(a[Max.front()]-a[Min.front()]<=k){l=mid+1;ok=1;break;}	
		}if(!ok)r=mid;
	}cout<<l-1<<endl;
	return 0;
}


你可能感兴趣的:(bzoj)