poj2823Sliding Window(线段树求最值)
裸线段树 这题时间卡的挺棒
1 #include <iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<algorithm> 5 #include<stdlib.h> 6 7 using namespace std; 8 #define N 1000010 9 #define INF 0xfffffff 10 int s[N<<2],lm[N<<2],sm[N<<2]; 11 int ma[N],mi[N],o; 12 void up(int l,int r,int w) 13 { 14 lm[w] = min(lm[w<<1],lm[w<<1|1]); 15 sm[w] = max(sm[w<<1],sm[w<<1|1]); 16 } 17 void build(int l,int r,int w) 18 { 19 if(l==r) 20 { 21 scanf("%d",&s[w]); 22 lm[w] = sm[w] = s[w]; 23 return ; 24 } 25 int m = (l+r)>>1; 26 build(l,m,w<<1); 27 build(m+1,r,w<<1|1); 28 up(l,r,w); 29 } 30 int query1(int a,int b,int l,int r,int w) 31 { 32 if(a<=l&&b>=r) 33 { 34 return lm[w]; 35 } 36 int m = (l+r)>>1,ans = INF; 37 if(a<=m) 38 ans = query1(a,b,l,m,w<<1); 39 if(b>m) 40 ans = min(ans,query1(a,b,m+1,r,w<<1|1)); 41 return ans; 42 } 43 int query2(int a,int b,int l,int r,int w) 44 { 45 if(a<=l&&b>=r) 46 { 47 return sm[w]; 48 } 49 int m = (l+r)>>1,ans = -INF; 50 if(a<=m) 51 ans = query2(a,b,l,m,w<<1); 52 if(b>m) 53 ans = max(ans,query2(a,b,m+1,r,w<<1|1)); 54 return ans; 55 } 56 int main() 57 { 58 int i,n,k; 59 while(scanf("%d%d",&n,&k)!=EOF) 60 { 61 build(1,n,1); 62 o = 1; 63 mi[1] = query1(1,k,1,n,1); 64 ma[1] = query2(1,k,1,n,1); 65 for(i = 2; i <= n-k+1 ; i++) 66 { 67 o++; 68 mi[o] = query1(i,i+k-1,1,n,1); 69 ma[o] = query2(i,i+k-1,1,n,1); 70 } 71 for(i = 1; i < o ; i++) 72 printf("%d ",mi[i]); 73 printf("%d\n",mi[o]); 74 for(i = 1; i < o ; i++) 75 printf("%d ",ma[i]); 76 printf("%d\n",ma[o]); 77 } 78 return 0; 79 }