GCD
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 4611 Accepted Submission(s): 1655
Problem Description
Give you a sequence of
N(N≤100,000) integers :
a1,...,an(0<ai≤1000,000,000). There are
Q(Q≤100,000) queries. For each query
l,r you have to calculate
gcd(al,,al+1,...,ar) and count the number of pairs
(l′,r′)(1≤l<r≤N)such that
gcd(al′,al′+1,...,ar′) equal
gcd(al,al+1,...,ar).
Input
The first line of input contains a number
T, which stands for the number of test cases you need to solve.
The first line of each case contains a number
N, denoting the number of integers.
The second line contains
N integers,
a1,...,an(0<ai≤1000,000,000).
The third line contains a number
Q, denoting the number of queries.
For the next
Q lines, i-th line contains two number , stand for the
li,ri, stand for the i-th queries.
Output
For each case, you need to output “Case #:t” at the beginning.(with quotes,
t means the number of the test case, begin from 1).
For each query, you need to output the two numbers in a line. The first number stands for
gcd(al,al+1,...,ar) and the second number stands for the number of pairs
(l′,r′) such that
gcd(al′,al′+1,...,ar′) equal
gcd(al,al+1,...,ar).
链接
一、题意
给定一个长度为N的数组和Q个查询,对于每个查询,要求输出数组中区间[L,R]的区间GCD和数组中有多少子区间的区间GCD等于该值(包括[L,R]自身)。
二、思路
对于区间GCD,可以使用RMQ来实现计算。记dp[i][j]为i开始,2的j次幂个数的GCD,则有递推关系dp[i][j] = GCD(dp[i][j - 1], dp[i + (1 << (j - 1))][j - 1])。查询时利用RMQ查询。
对于第二个问题,因为当左界不变时,随着区间的增大,区间GCD不可能增加,所以可以利用二分进行打表处理。枚举左界i,右界j从i开始,然后通过二分找到最大的右界j',使得[i,j']的区间GCD等于[i,j]的区间GCD,易知这之间的GCD都相等,记gcd为区间[i,j]的区间GCD,map[gcd]为区间GCD等于gcd的区间数,则有map[gcd] += j' - j + 1。
三、代码
#include
#include
#include
#include
#include
#include
#include
#include
#include