poj2823Sliding Window(线段树求最值)

时间:2021-12-03 09:55:50

链接

裸线段树 这题时间卡的挺棒

 #include <iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<stdlib.h> using namespace std;
#define N 1000010
#define INF 0xfffffff
int s[N<<],lm[N<<],sm[N<<];
int ma[N],mi[N],o;
void up(int l,int r,int w)
{
lm[w] = min(lm[w<<],lm[w<<|]);
sm[w] = max(sm[w<<],sm[w<<|]);
}
void build(int l,int r,int w)
{
if(l==r)
{
scanf("%d",&s[w]);
lm[w] = sm[w] = s[w];
return ;
}
int m = (l+r)>>;
build(l,m,w<<);
build(m+,r,w<<|);
up(l,r,w);
}
int query1(int a,int b,int l,int r,int w)
{
if(a<=l&&b>=r)
{
return lm[w];
}
int m = (l+r)>>,ans = INF;
if(a<=m)
ans = query1(a,b,l,m,w<<);
if(b>m)
ans = min(ans,query1(a,b,m+,r,w<<|));
return ans;
}
int query2(int a,int b,int l,int r,int w)
{
if(a<=l&&b>=r)
{
return sm[w];
}
int m = (l+r)>>,ans = -INF;
if(a<=m)
ans = query2(a,b,l,m,w<<);
if(b>m)
ans = max(ans,query2(a,b,m+,r,w<<|));
return ans;
}
int main()
{
int i,n,k;
while(scanf("%d%d",&n,&k)!=EOF)
{
build(,n,);
o = ;
mi[] = query1(,k,,n,);
ma[] = query2(,k,,n,);
for(i = ; i <= n-k+ ; i++)
{
o++;
mi[o] = query1(i,i+k-,,n,);
ma[o] = query2(i,i+k-,,n,);
}
for(i = ; i < o ; i++)
printf("%d ",mi[i]);
printf("%d\n",mi[o]);
for(i = ; i < o ; i++)
printf("%d ",ma[i]);
printf("%d\n",ma[o]);
}
return ;
}