The greatest common divisor of the sub-matrices of the nine-chapter algorithm surface test 29

Source: Internet
Author: User
Tags gcd greatest common divisor

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.