GCD
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 4611 Accepted Submission(s): 1655
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.
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 <iostream>
#include <sstream>
#include <iomanip>
#include <string>
#include <numeric>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <bitset>
#include <utility>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
using namespace std;
typedef long long LL;
const int MAXN = 100100;
const int MOD7 = 1e9 + 7;
const int MOD9 = 1e9 + 9;
const int INF = 2e9;
const double EPS = 1e-6;
const double PI = 3.14159265358979;
const int dir_4r[] = { -1, 1, 0, 0 };
const int dir_4c[] = { 0, 0, -1, 1 };
const int dir_8r[] = { -1, -1, -1, 0, 0, 1, 1, 1 };
const int dir_8c[] = { -1, 0, 1, -1, 1, -1, 0, 1 };
int input[MAXN];
int dp[MAXN][20];
map<int, LL> mp;
int GCD(int a, int b) {
int r;
while (b) {
r = a % b;
a = b;
b = r;
}
return a;
}
//RMQ初始化
void init(int n) {
for (int i = 0; i < n; ++i)
dp[i][0] = input[i];
for (int j = 1; (1 << j) <= n; ++j)
for (int i = 0; i + (1 << j) - 1 < n; ++i)
dp[i][j] = GCD(dp[i][j - 1], dp[i + (1 << (j - 1))][j - 1]);
}
int getGcd(int l, int r) {
int k = 0;
while ((1 << (k + 1)) <= r - l + 1)
k++;
return GCD(dp[l][k], dp[r - (1 << k) + 1][k]);
}
int main() {
int t, n, q, l, r;
scanf("%d", &t);
for (int kase = 1; kase <= t; ++kase) {
scanf("%d", &n);
for (int i = 0; i < n; ++i)
scanf("%d", input + i);
init(n);
//二分
mp.clear();
for (int i = 0; i < n; ++i) {//左界i
int j = i;
while (j < n) {//右界j
int gcd = getGcd(i, j);
l = j;
r = n - 1;
while (l < r) {
int mid = (l + r + 1) >> 1;
if (gcd > getGcd(i, mid))
r = mid - 1;
else
l = mid;
}
mp[gcd] += l - j + 1;
j = l + 1;
}
}
scanf("%d", &q);
printf("Case #%d:\n", kase);
for (int i = 0; i < q; ++i) {
scanf("%d%d", &l, &r);
l--;
r--;
int gcd = getGcd(l, r);
printf("%d %lld\n", gcd, mp[gcd]);
}
}
//system("pause");
return 0;
}