From: http://blog.csdn.net/svitter
Question: In 1 ~ In 200,000, take an interval and find the maximum number and the minimum number in the interval to find the difference between the two numbers.
Analysis: The line segment tree is obviously used by the range value. The interval size is 200000*4 = 8*10 ^ 5;
When performing a query, you can directly judge the relationship between L, R, and MID. At the beginning, you can directly judge the relationship with tree [root]. l, which is redundant,
The logic is incorrect.
# Include <iostream> # include <stdio. h> # include <stdlib. h> using namespace STD; const int INF = 0 xffffff; int maxv, MINV; struct node {int L, R; int mid () {return (L + r) /2;} int maxv, MINV; // maximum number and minimum number // node * lchild, * rchild; you can skip this operation by using an array, can be viewed as a full binary tree (space waste may exist)}; node tree [800010]; // four-fold leaf node void insert (INT root, int N, int Val) {// determine the leaf node if (tree [root]. L = tree [root]. r) {tree [root]. maxv = tree [root]. MINV = Val; Return;} // recursively update tree [root]. MINV = min (tree [root]. MINV, Val); tree [root]. maxv = max (tree [root]. maxv, Val); // The interval node is currently used to find the leaf node if (n <tree [root]. mid () {insert (root * 2 + 1, n, Val);} else {insert (root * 2 + 2, N, Val );}} void buildtree (INT root, int L, int R) {// create the current node tree [root]. L = L; tree [root]. R = r; tree [root]. maxv =-INF; tree [root]. MINV = inf; // recursive call to create a subtree if (L! = R) {buildtree (root * 2 + 1, L, (L + r)/2); buildtree (root * 2 + 2, (L + r) /2 + 1, R) ;}} void query (INT root, int L, int R) {// recursive termination condition if (L <tree [root]. l | r> tree [root]. r) return; // judgment condition: the condition fully complies with the IF (L = tree [root] range. L & R = tree [root]. r) {maxv = max (maxv, tree [root]. maxv); MINV = min (MINV, tree [root]. MINV); return;} If (r <= tree [root]. mid () query (root * 2 + 1, L, R); else if (L> tree [root]. mid () query (root * 2 + 2, L, R); else {query (root * 2 + 1, L, tree [root]. mid (); query (root * 2 + 2, tree [root]. mid () + 1, R) ;}} int main () {int N, Q; int val; int A, B; // search for the interval [, b] // while (scanf ("% d", & N, & Q) scanf ("% d", & N, & Q ); {buildtree (0, 1, n); For (INT I = 0; I <n; I ++) {scanf ("% d", & Val ); insert (0, I, Val) ;}// used to test the generation of the Line Segment tree // For (INT I = 0; I <7; I ++) // {// printf ("No: % d, \ NL: % d, \ Nr: % d, \ Nmax: % d, \ Nmin: % d, \ n ", I, tree [I]. l, tree [I]. r, tree [I]. maxv, tree [I]. MINV); //} while (Q --) {maxv =-INF, MINV = inf; scanf ("% d", & A, & B ); query (0, a, B); // printf ("MAX: % d \ Nmin: % d \ n", maxv, MINV ); printf ("% d \ n", maxv-MINV) ;}} return 0 ;}