The line segment tree is a binary tree, denoted by T (A, B), and the parameter A, a, is the interval [a, a], where b-a is called the length of the interval, denoted as L.
Data:
struct node{ int left,right; // interval around value Node *leftchild; Node *rightchild; };
Establishment of Segment tree:
Node *build (intLintR)//build a two-fork tree{Node*root =NewNode; Root->left =l; Root->right = R;//set the node interval.Root->leftchild =NULL; Root->rightchild =NULL; if(L +1< R)//L>1 The case, that is, not the leaf node. { intMid = (r+l) >>1; Root->leftchild =build (L, mid); Root->rightchild =Build (Mid, R); } returnRoot;}
Insert a line segment [C,d]:Add a cover field to calculate the number of times a line segment is overwritten, and cover 0 when setting up a two-fork tree.
voidInsert (intCintD, Node *root) { if(c<= root->left&&d>= root->Right ) Rootcover++; Else { //comparing the upper bound of the lower bound with Zuozi if(C < (root->left+ root->right)/2) Insert (C,d, root->leftchild); //comparing upper bound with lower bound of right subtree if(d > (root->left+ root->right)/2) Insert (C,d, root->rightchild);//Note that if an interval spans the left and right sons, then do not worry, it will match the left son, one of the sons of a single node }}
Delete a line segment [C,d]:
void Delete (intint D, Node *root) { if(c<= root->left&&d >= root-> right) root, cover= root-> cover-1; Else { if(C < (root->left+ root->right)/2 ) Delete (C,d, root-> leftchild ); if (d > (root->left+ root->right)/2 ) Delete (c,d, root->rightchild);} }
Question:given a huge n*n matrix, we need to query the GCD (greatest common divisor greatest common divisor) of numbers in any Given Submatrix Range (x1,y1,x2,y2). Design A-preprocess the matrix to accelerate the "query speed." Extra space should is less than O (n^2) and the preprocess time complexity should is as litte as possible. Solution:for each row a[i] in the matrix A, we build a segment tree. The tree allows us to query GCD (a[i][a. b] greatest common divisor in O (log n) time of row A to column B (excluding B). The memory complexity of each segment tree are O (n), which gives us O (n^2) Total memory complexity. time complexity, O (n2) build segment tree, & Nbsp;o (R * Log (c)) lookup, where R and C is the number of rows and columns in the query. GCD realization: The divisor and the remainder for the divisor congruence, so the divisor and divisor of the GCD is the remainder and the divisor of the GCD, so recursive or cyclic solution.
int $ * , TMP; while (b!=0= a%== =<< a << Endl;
Line segment Trees (segment tree)