题解:树上的数
算法
算法
到这一步,我们需要进行一些容斥了。
首先,我们把问题转为两两距离之和减去不互质的点对距离和。
之后,对于每一个数,我们把所有的平方因子除去,直到不存在平方因子,因为互质只和有哪些因子有关而不是多少个因子。
考虑对于每一个质因子计算答案,计算这个质因子
发现一些合数是被多算了的,所以我们需要容斥,质因子个数为奇数则加,否则减,这样可以满足恰好选一次。
至于质因子分解,提前
算法
接下来到了树上,考虑用一些东西来快速维护。
算法
算法
#include<bits/stdc++.h>
#define re register
using namespace std;
const int Mxdt=300000; //单次大小
inline char gc(){
static char buf[Mxdt],*p1=buf,*p2=buf;
return p1==p2&&(p2=(p1=buf)+fread(buf,1,Mxdt,stdin),p1==p2)?EOF:*p1++;
}
inline int read(){
re int t=0;re char v=gc();
while(v<'0')v=gc();
while(v>='0')t=(t<<3)+(t<<1)+v-48,v=gc();
return t;
}
int c[300002],n,head[300002],cnt,a[300002],siz[300002],son[300002],dep[300002],num,ip[300002],cc[300002],mu[300002],vv[300002];
long long sum[300002],ans,sdp;
struct edge{
int to,next;
}e[600002];
inline void add(re int x,re int y){e[++cnt]=(edge){y,head[x]};head[x]=cnt;}
vector<int>v[300002];
inline void dfs(re int x,re int y){
siz[x]=1,dep[x]=dep[y]+1;
for(re int i=head[x];i;i=e[i].next)
if(e[i].to^y){
dfs(e[i].to,x);
siz[x]+=siz[e[i].to];
if(siz[e[i].to]>siz[son[x]])son[x]=e[i].to;
}
}
inline void add(re int x){++num,sdp+=dep[x];for(re int i=0;i<v[a[x]].size();++i)++c[v[a[x]][i]],sum[v[a[x]][i]]+=dep[x];}
inline void del(re int x){--num,sdp-=dep[x];for(re int i=0;i<v[a[x]].size();++i)--c[v[a[x]][i]],sum[v[a[x]][i]]-=dep[x];}
inline void addd(re int x,re int y){
add(x);
for(re int i=head[x];i;i=e[i].next)if(e[i].to^y)addd(e[i].to,x);
}
inline void del(re int x,re int y){
del(x);
for(re int i=head[x];i;i=e[i].next)if(e[i].to^y)del(e[i].to,x);
}
inline void calc(re int x,re int y,re int z){
ans+=sdp-1ll*num*dep[z]+1ll*num*(dep[x]-dep[z]);
for(re int i=0;i<v[a[x]].size();++i)(cc[v[a[x]][i]]&1)?ans-=1ll*(dep[x]-dep[z])*c[v[a[x]][i]]+sum[v[a[x]][i]]-1ll*dep[z]*c[v[a[x]][i]]:ans+=1ll*(dep[x]-dep[z])*c[v[a[x]][i]]+sum[v[a[x]][i]]-1ll*dep[z]*c[v[a[x]][i]];
for(re int i=head[x];i;i=e[i].next)if(e[i].to^y)calc(e[i].to,x,z);
}
inline void dfs1(re int x,re int y,re int z){
for(re int i=head[x];i;i=e[i].next)if((e[i].to^y)&&(e[i].to^son[x]))dfs1(e[i].to,x,1);
if(son[x])dfs1(son[x],x,0);
for(re int i=0;i<v[a[x]].size();++i){
(cc[v[a[x]][i]]&1)?ans-=sum[v[a[x]][i]]-1ll*dep[x]*c[v[a[x]][i]]:ans+=sum[v[a[x]][i]]-1ll*dep[x]*c[v[a[x]][i]];
}
add(x),ans+=sdp-1ll*num*dep[x];
for(re int i=head[x];i;i=e[i].next)if((e[i].to^y)&&(e[i].to^son[x]))calc(e[i].to,x,x),addd(e[i].to,x);
if(z)del(x,y);
}
signed main(){
for(re int i=1;i<=300000;++i)vv[i]=1;
for(re int i=2;i<=300000;++i){
if(mu[i])continue;
v[i].push_back(i);
if(!ip[i])cc[i]=1,vv[i]=i;
for(re int j=i+i;j<=300000;j+=i){
if(!ip[i])vv[j]*=i;
cc[j]+=(!ip[i]),v[j].push_back(i),ip[j]=1;
}
if(i<=2000)for(re int j=i*i;j<=300000;j+=i*i)mu[j]=1;
}
n=read();
for(re int i=1;i<=n;++i){a[i]=vv[read()];
}
for(re int i=1,x,y;i<n;++i)x=read(),y=read(),add(x,y),add(y,x);
dfs(1,0),dfs1(1,0,0);
printf("%lld",ans);
}
题外话:想题的过程中想到了一个 trick:即将路径长度和变为断掉一条边,求两个子树满足条件的对数,但很遗憾,没有想到一个好的方法。