1. 程式人生 > >[POJ2823] [POJ0604月賽] Sliding Window [單調佇列/線段樹]

[POJ2823] [POJ0604月賽] Sliding Window [單調佇列/線段樹]

大家都知道的單調佇列模板題

被卡時間了,難受 poj上G++過不去 只能換C++

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<cctype>
using namespace std;
#define getchar() (frS==frT&&(frT=(frS=frBB)+fread(frBB,1,1<<12,stdin),frS==frT)?EOF:*frS++)
char frBB[1<<12]={},*frS=frBB,*frT=frBB; int N,K,head=1,head2=1; int lst[1000005]={}; int tme[1000005]={}; int ans[1000005]={}; int lst2[1000005]={}; int tme2[1000005]={}; inline int read() { bool w=0;int x=0;char ch=getchar(); while(!isdigit(ch))w|=(ch=='-'),ch=getchar(); while(isdigit(ch))x=x*10+(ch-'0'),ch=getchar(
); return w?-x:x; } int main() { N=read(); K=read(); for(register int tmp,i=1;i<=N;++i) { tmp=read(); lst[0]=lower_bound(lst+head,lst+1+lst[0],-tmp)-lst; lst[lst[0]]=-tmp; tme[lst[0]]=i; head=upper_bound(tme+head,tme+1+lst[0],i-K)-tme; if(i>=K)ans[++ans[0]]=-lst[head]; lst2[0]=lower_bound
(lst2+head2,lst2+1+lst2[0],tmp)-lst2; lst2[lst2[0]]=tmp; tme2[lst2[0]]=i; head2=upper_bound(tme2+head2,tme2+1+lst2[0],i-K)-tme2; if(i>=K)printf("%d ",lst2[head2]); } putchar('\n'); for(register int i=1;i<=ans[0];++i)printf("%d ",ans[i]); return 0; }

upper_bound和lower_bound有那麼慢嗎(( 不過改成手寫二分也是tle

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<cctype>
using namespace std;
#define getchar() (frS==frT&&(frT=(frS=frBB)+fread(frBB,1,1<<12,stdin),frS==frT)?EOF:*frS++)
char frBB[1<<12]={},*frS=frBB,*frT=frBB;
int N,K,head=1,head2=1;
int lst[1000005]={};
int tme[1000005]={};
int ans[1000005]={};
int lst2[1000005]={};
int tme2[1000005]={};
inline int read()
{
	bool w=0;int x=0;char ch=getchar();
	while(!isdigit(ch))w|=(ch=='-'),ch=getchar();
	while(isdigit(ch))x=x*10+(ch-'0'),ch=getchar();
	return w?-x:x;
}
int lowb(int* array,int l,int r,int key)
{
	register int mid; ++r;
	while(l<r)
	{
		mid=l+r>>1;
		if(array[mid]<key)l=mid+1;
		else r=mid;
	}
	return l;
}
int uppb(int* array,int l,int r,int key)
{
	register int mid; ++r;
	while(l<r)
	{
		mid=l+r>>1;
		if(array[mid]<=key)l=mid+1;
		else r=mid;
	}
	return l;
}
int main()
{
	N=read(); K=read();
	for(register int tmp,i=1;i<=N;++i)
	{
		tmp=read();
		
		lst[0]=lowb(lst,head,lst[0],-tmp);
		lst[lst[0]]=-tmp; tme[lst[0]]=i;
		head=uppb(tme,head,lst[0],i-K);
		if(i>=K)ans[++ans[0]]=-lst[head];
		
		lst2[0]=lowb(lst2,head2,lst2[0],tmp);
		lst2[lst2[0]]=tmp; tme2[lst2[0]]=i;
		head2=uppb(tme2,head2,lst2[0],i-K);
		if(i>=K)printf("%d ",lst2[head2]);
	}
	putchar('\n');
	for(register int i=1;i<=ans[0];++i)printf("%d ",ans[i]);
	return 0;
}

難道我不該二分(???