标签:query int insert ios main div 最大数和最小数 poj 全局变量
此题为入门级线段树
题意:给定Q(1<=Q<=200000)个数A1A2…AQ,多次求任一区间Ai-Aj中最大数和最小数的差
1 #include<algorithm> 2 #include<cstdio> 3 #include<string> 4 #include<string.h> 5 #include<iostream> 6 using namespace std; 7 typedef long long LL; 8 const int INF = 0x7FFFFFFF; 9 const int maxn = 1e3 + 10; 10 11 int minV = INF; 12 int maxV = -INF; 13 struct Node 14 { 15 int L, R; 16 int minV, maxV; 17 //Node *pLeft, *pRight; 18 int Mid() 19 { 20 return (L + R) / 2; 21 } 22 }; 23 Node tree[800010];//4倍叶子节点的数量就够 24 25 void BuildTree(int root, int L, int R) 26 { 27 tree[root].L = L; 28 tree[root].R = R; 29 tree[root].minV = INF; 30 tree[root].maxV = -INF; 31 if (L != R) 32 { 33 BuildTree(2 * root + 1, L, (L + R) / 2); 34 BuildTree(2 * root + 2, (L + R) / 2 + 1, R); 35 } 36 } 37 38 void Insert(int root, int i, int v) 39 //将第i个数,其值为v,插入线段树 40 { 41 if (tree[root].L == tree[root].R) 42 { 43 //成立则亦有tree[root].R==i 44 tree[root].minV = tree[root].maxV = v; 45 return; 46 } 47 tree[root].minV = min(tree[root].minV, v); 48 tree[root].maxV = max(tree[root].maxV, v); 49 if (i <= tree[root].Mid()) 50 Insert(2 * root + 1, i, v); 51 else 52 Insert(2 * root + 2, i, v); 53 } 54 55 void Query(int root, int s, int e) 56 //查询区间[s,e]中的最小值和最大值,如果更优就记在全局变量里 57 { 58 if (tree[root].minV >= minV&&tree[root].maxV <= maxV) 59 return; 60 if (tree[root].L == s&&tree[root].R == e) 61 { 62 minV = min(minV, tree[root].minV); 63 maxV = max(maxV, tree[root].maxV); 64 return; 65 } 66 if (e <= tree[root].Mid()) 67 Query(2 * root + 1, s, e); 68 else if (s > tree[root].Mid()) 69 Query(2 * root + 2, s, e); 70 else 71 { 72 Query(2 * root + 1, s, tree[root].Mid()); 73 Query(2 * root + 2, tree[root].Mid() + 1, e); 74 } 75 } 76 77 int main() 78 { 79 int n, q, h; 80 int i, j, k; 81 scanf("%d%d", &n, &q); 82 BuildTree(0, 1, n); 83 for (i = 1; i <= n; i++) 84 { 85 scanf("%d", &h); 86 Insert(0, i, h); 87 } 88 for (i = 0; i < q; i++) 89 { 90 int s, e; 91 scanf("%d%d", &s, &e); 92 minV = INF; 93 maxV = -INF; 94 Query(0, s, e); 95 printf("%d\n", maxV - minV); 96 } 97 return 0; 98 }
标签:query int insert ios main div 最大数和最小数 poj 全局变量
原文地址:http://www.cnblogs.com/demian/p/6081999.html