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.
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).
For each query print the result in a separate line.
3 2 6 3 5 1 2 3 4 6
1 2 2 0 1
7 10 20 3 15 1000 60 16 10 1 2 3 4 5 6 10 20 60 1000
14 0 2 2 2 0 2 2 1 1
考數據結構的題,也是考數學功底的題,對於一段(l,r)從(l,l+1)開始的gcd嚴格單調遞減,所以可用二分查出(l,r)裏和(l,l)公約數一樣的最大長度,之後又是新一輪的查找,因爲一個數不會超過31個素因數,所以新一輪的查找不會很多,自己可以模擬一下,最多30次。具體做法就是枚舉起點,終點始終是n,進行這種查找,找出來的數用map保存,最後的詢問直接map回答。
這裏還要求區間取GCD,線段樹是不行的,因爲此題卡了常數,所以得用ST算法,就算是ST,也得用位運算加速,即rmq的時候,不能用log,只能用31-__builtin_clz(v-s+1),不然還是超時。。。
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<ctime>
#include<string>
#include<cstring>
#include<algorithm>
#include<fstream>
#include<queue>
#include<stack>
#include<vector>
#include<cmath>
#include<iomanip>
#include<map>
#define rep(i,n) for(i=1;i<=n;i++)
#define MM(a,t) memset(a,t,sizeof(a))
#define INF 1e9
typedef long long ll;
#define mod 1000000007
using namespace std;
map<int,ll> mp;
int dp[100020][20],n,m;
int gcd(int a,int b){
if(a==0) return b;
if(b==0) return a;
if(a<b) return gcd(b,a);
if(a%b==0) return b;
else return gcd(b,a%b);
}
void makermq(){
int i,j;
for(j=1;(1<<j)<=n;j++)
for(i=1;i+(1<<j)-1<=n;i++)
dp[i][j]=gcd(dp[i][j-1],dp[i+(1<<(j-1))][j-1]);
}
int rmq(int s,int v){
int k=31-__builtin_clz(v-s+1);
return gcd(dp[s][k],dp[v-(1<<k)+1][k]);
}
int main()
{
int i,j;
while(scanf("%d",&n)!=EOF){
MM(dp,0);
rep(i,n) scanf("%d",&dp[i][0]);
makermq();
mp.clear();
rep(i,n){
int st=i,l,r,tmp,mid,v;
while(st<=n){
v=st; l=st; r=n; tmp=rmq(i,l);
while(l<=r){
mid=(l+r)>>1;
if(rmq(i,mid)==tmp){
l=mid+1;
v=mid;
}
else r=mid-1;
}
mp[tmp]+=v-st+1;
st=v+1;
}
}
scanf("%d",&m);
while(m--){
int tmp;
scanf("%d",&tmp);
printf("%I64d\n",mp[tmp]);
}
}
return 0;
}