poj 3264线段树
题意: 给出一个数列, 找出一个区间中的最大值与最小值, 并求它们的差。
思路: 简单线段树。
AC代码:
View Code
1 #include <cstdio> 2 #include <iostream> 3 #include <string> 4 #include <cstring> 5 #include <queue> 6 using namespace std; 7 const int N = 50100; 8 struct NODE 9 { 10 int left, right, min_v, max_v; 11 }node[N*4]; 12 13 int n, q, value[N]; 14 15 void build(int left, int right, int pos) 16 { 17 node[pos].left = left; 18 node[pos].right = right; 19 if(left == right) 20 { 21 node[pos].max_v = node[pos].min_v = value[left]; 22 return ; 23 } 24 25 int mid = (left+right)/2; 26 build(left, mid, pos*2); 27 build(mid+1, right, pos*2+1); 28 node[pos].max_v = max(node[pos*2].max_v, node[pos*2+1].max_v); 29 node[pos].min_v = min(node[pos*2].min_v, node[pos*2+1].min_v); 30 } 31 32 int findmax(int l, int r, int pos) 33 { 34 if(l == node[pos].left && r == node[pos].right) 35 { 36 return node[pos].max_v; 37 } 38 39 int mid = (node[pos].left+node[pos].right)/2; 40 41 if(r <= mid) 42 { 43 return findmax(l, r, 2*pos); 44 } 45 else if(l > mid) 46 { 47 return findmax(l, r, 2*pos+1); 48 } 49 else 50 { 51 return max( findmax(l,mid, 2*pos), findmax(mid+1, r, 2*pos+1) ); 52 } 53 } 54 55 int findmin(int l, int r, int pos) 56 { 57 if(l == node[pos].left && r == node[pos].right) 58 { 59 return node[pos].min_v; 60 } 61 62 int mid = (node[pos].left+node[pos].right)/2; 63 64 if(r <= mid) 65 { 66 return findmin(l, r, 2*pos); 67 } 68 else if(l > mid) 69 { 70 return findmin(l, r, 2*pos+1); 71 } 72 else 73 { 74 return min( findmin(l,mid, 2*pos), findmin(mid+1, r, 2*pos+1) ); 75 } 76 } 77 78 int main() 79 { 80 int a, b, max_v, min_v; 81 while(scanf("%d%d", &n, &q) != EOF) 82 { 83 for(int i=1; i<=n; i++) 84 { 85 scanf("%d", &value[i]); 86 } 87 88 build(1, n, 1); 89 90 while(q--) 91 { 92 scanf("%d%d", &a, &b); 93 max_v = findmax(a, b, 1); 94 min_v = findmin(a, b, 1); 95 //cout<<max_v<<" "<<min_v<<endl; 96 printf("%d\n", max_v - min_v); 97 } 98 } 99 return 0; 100 }


浙公网安备 33010602011771号