bzoj #3853. GCD Array 题解

Topic portal

Main idea: give a sequence aaa , each position is initially0 00 , there are two operations: 1. Given, d, vn, d, vn,d,v , let all satisfygcd ⁡ (n, x) = d \gcd(n,x)=dgcd(n,x)=d isa [x] a [x]a [ x ] plusvvv ; 2, requestaaA certain prefix sum.

answer

Maintain an auxiliary array fff,满足 a i = ∑ d ∣ i f d a_i=\sum_{d|i}f_d ai=difd

Consider each ax a_xax, Its increment in each operation is v [(x, n) = d] v[(x,n)=d]v[(x,n)=d],推一推就是:
     v [ ( x , n ) = d ] = v [ ( x d , n d ) = 1 ] = ∑ k ∣ ( x d , n d ) v μ ( k ) = ∑ d k ∣ x , k ∣ n d v μ ( k ) \begin{aligned} &~~~~v[(x,n)=d]\\ &=v[(\frac x d,\frac n d)=1]\\ &=\sum_{k|(\frac x d,\frac n d)}v\mu(k)\\ &=\sum_{dk|x,k|\frac n d}v\mu(k) \end{aligned}     v[(x,n)=d]=v [ (dx,dn)=1]=k(dx,dn)v μ ( k )=dkx,kdnv μ ( k )

It can be found that a nd \dfrac nd is enumerateddnFactor kkk , thendk dkd k must meet the condition ofxxfactor of x , so you can makefdk f_{dk}fdkAdd v μ (k) v\mu(k)v μ ( k )

再考虑求解, ∑ i = 1 x a i = ∑ i = 1 x ∑ j ∣ i f j = ∑ j = 1 n f j ⌊ x j ⌋ \sum_{i=1}^x a_i=\sum_{i=1}^x\sum_{j|i}f_j=\sum_{j=1}^n f_j\lfloor \dfrac x j \rfloor i=1xai=i=1xjifj=j=1nfjjx , so just set a divisible block, hereffis requiredThe prefix sum of f , so it needs to be maintained by a tree array, and the complexity isO (nn log ⁡ n) O(n\sqrt n \log n)O ( nn logn)

code show as below:

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
#define maxn 200010
#define ll long long

int n,m;ll tr[maxn];
void add(int x,int y){
    
    for(;x<=maxn-10;x+=(x&-x))tr[x]+=y;}
ll sum(int x){
    
    ll re=0;for(;x>=1;x-=(x&-x))re+=tr[x];return re;}
int mu[maxn],prime[maxn],t=0;
bool v[maxn];
struct edge{
    
    int y,next;}e[maxn<<4];
int first[maxn],len=0;
void buildroad(int x,int y){
    
    e[++len]=(edge){
    
    y,first[x]};first[x]=len;}
void work(){
    
    
	mu[1]=1;for(int i=2;i<=maxn-10;i++){
    
    
		if(!v[i])prime[++t]=i,mu[i]=-1;
		for(int j=1;j<=t&&i*prime[j]<=maxn-10;j++){
    
    
			v[i*prime[j]]=true;
			if(i%prime[j]==0)break;
			mu[i*prime[j]]=-mu[i];
		}
	}
	for(int i=1;i<=maxn-10;i++)
	for(int j=i;j<=maxn-10;j+=i)buildroad(j,i);
}

int main()
{
    
    
	work();int Case=0;
	while(scanf("%d %d",&n,&m),n!=0&&m!=0)
	{
    
    
		printf("Case #%d:\n",++Case);
		memset(tr,0,sizeof(tr));
		for(int i=1,id,N,D,V;i<=m;i++)
		{
    
    
			scanf("%d",&id);
			if(id==1){
    
    
				scanf("%d %d %d",&N,&D,&V);
				if(N%D==0)for(int j=first[N/D];j;j=e[j].next)add(e[j].y*D,V*mu[e[j].y]);
			}else{
    
    
				scanf("%d",&N);ll ans=0;
				for(int l=1,r;l<=N;l=r+1){
    
    
					r=N/(N/l);
					ans+=N/l*(sum(r)-sum(l-1));
				}
				printf("%lld\n",ans);
			}
		}
	}
}

Guess you like

Origin blog.csdn.net/a_forever_dream/article/details/107562516
gcd