Nine Chapters count judges Net-original website
http://www.jiuzhang.com/problem/29/
Topics
Given the n*n matrix, you need to query the greatest common divisor of all the numbers in any sub-matrices. Please give a design idea, preprocessing the matrix, speed up the query. Additional space complexity is required within O (n^2).
Answer
Constructs a two-dimensional line segment tree. Preprocessing time O (n^2), each query O (log n)
Interviewer Angle
This topic needs to have a certain data structure foundation. The problem that can be solved by line-segment trees (Interval tree) is those that satisfy the binding law. Greatest common divisor is an operation that satisfies the binding law. So there, GCD (a,b,c,d) = GCD (GCD (A, B), GCD (C, D)). There are also Pi,sum,xor (product, and, XOR) operations with a binding law. The basic idea of line-segment tree is that the interval [1,n] is divided into [1, N/2], [N/2+1,n] two sub-ranges, and then each sub-range continues to do two points until the interval length is 1. The results of the operation of the interval are maintained on each interval (e.g. gcd,sum), when the result of an interval is queried, the interval is mapped to a number of disjoint intervals on the segment tree, and the results of these intervals are combined to obtain the answer. It can be shown that any interval can be mapped to a segment tree that does not exceed the O (log n) interval. Described above is a one-dimensional segment tree, for the two-dimensional situation, you can use four points or a cross-sectional method to construct a line segment tree.
The greatest common divisor of the sub-matrices of the nine-chapter algorithm surface test 29