【CODEFORCES】 D. CGCDSSQ

来源:互联网 发布:四川农大网络教育专业 编辑:程序博客网 时间:2024/05/01 14:08

D. CGCDSSQ
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

Given a sequence of integers a1, ..., an and q queries x1, ..., xq on it. For each query xi you have to count the number of pairs (l, r)such that 1 ≤ l ≤ r ≤ n and gcd(al, al + 1, ..., ar) = xi.

 is a greatest common divisor of v1, v2, ..., vn, that is equal to a largest positive integer that divides all vi.

Input

The first line of the input contains integer n, (1 ≤ n ≤ 105), denoting the length of the sequence. The next line contains n space separated integers a1, ..., an, (1 ≤ ai ≤ 109).

The third line of the input contains integer q, (1 ≤ q ≤ 3 × 105), denoting the number of queries. Then follows q lines, each contain an integer xi, (1 ≤ xi ≤ 109).

Output

For each query print the result in a separate line.

Sample test(s)
input
32 6 3512346
output
12201
input
710 20 3 15 1000 60 16101234561020601000
output
14022202211
题解:题目大意是说给你一个序列,然后有q个询问,每个询问描述成一个正整数c,问你在这个序列中,区间上的最大公约数等于c的区间共有多少个。

因为我们只关心个数而并不关心区间,所以可以递推来写。假设我们知道了第以i个数为结尾的所有区间上的最大公约数,我们就可以统计他的个数。而我们在讨论i+1的时候,我们是可以推出以第i+1个数结尾的所有最大公约数的(和第i个数的结果依次取GCD即可),然后统计个数(其实就是直接加进去)。最后记得每次把第i个数的结果加到ANS里面就行了。

代码并不长,时间也不长。果然是因为map太快了么= =||

#include <iostream>#include <cstring>#include <map>#include <cstdio>using namespace std;int a[100005],n,q,c;int gcd(int a,int b){    if (!b) return a;    else return gcd(b,a%b);}map<int,long long> ans;map<int,int> last;map<int,int> now;map<int,int>::iterator itr;int main(){    scanf("%d",&n);    for (int i=0;i<n;i++) scanf("%d",&a[i]);    ans.clear();    for (int i=0;i<n;i++)    {        swap(last,now);        now.clear();        for (itr=last.begin();itr!=last.end();itr++)            now[gcd(itr->first,a[i])]+=itr->second;        now[a[i]]++;        for (itr=now.begin();itr!=now.end();itr++)            ans[itr->first]+=itr->second;    }    scanf("%d",&q);    for (int i=0;i<q;i++)    {        scanf("%d",&c);        printf("%I64d\n",ans[c]);    }    return 0;}

0 0
原创粉丝点击