[Codeforces475D]CGCDSSQ（数学相关+二分）

代码

#include<map>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define Pow 18
using namespace std;
int n,val[100010],st[100010][20],q,r[300010],lg2[100010];
map<int,long long> ans;
int gcd(int a,int b){
if (a==0||b==0) return 0;
int r=a%b;
while (r!=0){
a=b;b=r;r=a%b;
}
return b;
}
void get_st(){
for (int i=1,p=0;i<=n;i++){
while ((1<<p)<=i) ++p;
lg2[i]=p-1;
}
for (int i=1;i<=n;i++) st[i][0]=val[i];
for (int j=1;j<=Pow;j++)
for (int i=1;i<=n;i++)
if (i+(1<<(j-1))<=n)
st[i][j]=gcd(st[i][j-1],st[i+(1<<(j-1))][j-1]);
}
int get_gcd(int l,int r){
int j=lg2[r-l+1],tmp;
tmp=r-(1<<j)+1;
return gcd(st[l][j],st[tmp][j]);
}
int divide(int l,int r,int S,int x){
int mid,v,ans=n+1;
while (l<=r){
mid=(l+r)>>1;
v=get_gcd(S,mid);
if (v<=x){
ans=min(ans,mid);r=mid-1;
}else l=mid+1;
}
return ans;
}
void work(int s){
int g=val[s],last,ptr,v;
last=ptr=s;
while (ptr<=n){
ptr=divide(s,n,s,g-1);
ans[g]+=(long long)(ptr-last);//累加当前gcd下的答案
last=ptr;g=get_gcd(s,ptr);//指针后移
}
}
int main()
{
scanf("%d",&n);
for (int i=1;i<=n;i++) scanf("%d",&val[i]);
get_st();
for (int i=1;i<=n;i++) work(i);
scanf("%d",&q);
for (int i=1;i<=q;i++){
int x;scanf("%d",&x);
printf("%I64d\n",ans[x]);
}
return 0;
}


©️2019 CSDN 皮肤主题: 技术工厂 设计师: CSDN官方博客