标签:des style blog http io ar color os sp
6 3 1 7 3 4 2 5 1 5 4 6 2 2
静态线段树水题Orz,区间查找最大值和最小值做差就可以了Orz
1 /*Author:WNJXYK*/ 2 #include<cstdio> 3 using namespace std; 4 5 struct Btree{ 6 int left,right; 7 int num; 8 int max,min; 9 }; 10 const int Maxn=50000; 11 Btree tree[Maxn*4+10]; 12 13 int n,q; 14 int num[Maxn+10]; 15 16 inline int remin(int a,int b){ 17 if (a<b) return a; 18 return b; 19 } 20 21 inline int remax(int a,int b){ 22 if (a>b) return a; 23 return b; 24 } 25 26 void build(int x,int left,int right){ 27 tree[x].left=left; 28 tree[x].right=right; 29 if (left==right){ 30 tree[x].max=tree[x].min=tree[x].num=num[left]; 31 }else{ 32 int mid=(left+right)/2; 33 build(x*2,left,mid); 34 build(x*2+1,mid+1,right); 35 tree[x].max=remax(tree[x*2].max,tree[x*2+1].max); 36 tree[x].min=remin(tree[x*2].min,tree[x*2+1].min); 37 } 38 } 39 40 int queryMax(int x,int left,int right){ 41 if (left<=tree[x].left && tree[x].right<=right){ 42 return tree[x].max; 43 }else{ 44 int res=0; 45 int mid=(tree[x].left+tree[x].right)/2; 46 if (left<=mid) res=remax(res,queryMax(x*2,left,right)); 47 if (mid+1<=right) res=remax(res,queryMax(x*2+1,left,right)); 48 return res; 49 } 50 } 51 52 int queryMin(int x,int left,int right){ 53 if (left<=tree[x].left && tree[x].right<=right){ 54 return tree[x].min; 55 }else{ 56 int res=2147483647; 57 int mid=(tree[x].left+tree[x].right)/2; 58 if (left<=mid) res=remin(res,queryMin(x*2,left,right)); 59 if (mid+1<=right) res=remin(res,queryMin(x*2+1,left,right)); 60 return res; 61 } 62 } 63 64 int main(){ 65 scanf("%d%d",&n,&q); 66 for (int i=1;i<=n;i++) scanf("%d",&num[i]); 67 build(1,1,n); 68 for (int i=1;i<=q;i++){ 69 int left,right; 70 scanf("%d%d",&left,&right); 71 printf("%d\n",queryMax(1,left,right)-queryMin(1,left,right)); 72 } 73 return 0; 74 }
BZOJ 1636: [Usaco2007 Jan]Balanced Lineup
标签:des style blog http io ar color os sp
原文地址:http://www.cnblogs.com/WNJXYK/p/4162344.html