赛时过了这道题(T6)结果 极限一等了。
首先考虑把前 20 分的 subtask 给混到手。这里我用的是树剖,后来发现树剖时就预处理了 dfs 序、子树大小等信息。
接着考虑对于每个因子 ,有哪些 是 的倍数。用 从小到大存储这些 ,方便之后对字数的查找。
然后来统计题目所要求的点对。枚举点对定义中的 。二分查找 中有多少个点位于以 为根的子树中。
定义 表示以 为根的子树中有多少个点 的 含有因子 。
定义 表示在以 为根的子树中,以 为根的子树节点对 的贡献。
对于每个 ,枚举其儿子节点 ,此时对答案的贡献为 。注意对于每个 ,答案要减去 ,即点对 的贡献。
#include<cstdio>
#include<vector>
#include<algorithm>
#include<map>
using namespace std;
int n,a[100010],dep[100010],fa[100010],son[100010],siz[100010],top[100010],b[100010],dfn[100010],cnt,rep[100010];
vector<int>graph[100010],sum[100010];
map<int,int>c[100010];
void dfs1(int now,int father)
{
dep[now]=dep[father]+1;
fa[now]=father;
siz[now]=1;
for(auto to:graph[now])
{
if(to==father) continue;
dfs1(to,now);
siz[now]+=siz[to];
if(siz[son[now]]<siz[to]) son[now]=to;
}
}
void dfs2(int now,int root)
{
dfn[now]=++cnt;
rep[cnt]=now;
top[now]=root;
if(son[now]) dfs2(son[now],root);
for(auto to:graph[now])
{
if(to==fa[now]||to==son[now]) continue;
dfs2(to,to);
}
}
int lca(int x,int y)
{
while(top[x]!=top[y])
{
if(dep[top[x]]<dep[top[y]]) swap(x,y);
x=fa[top[x]];
}
if(dep[x]<dep[y]) return x;
else return y;
}
void dfs3(int now)
{
b[now]=1;
for(auto to:graph[now])
{
if(to==fa[now]) continue;
dfs3(to);
auto tmp1=lower_bound(sum[a[now]].begin(),sum[a[now]].end(),dfn[to]);
if(tmp1==sum[a[now]].begin()) continue;
auto tmp2=upper_bound(sum[a[now]].begin(),sum[a[now]].end(),dfn[to]+siz[to]-1);
b[now]+=tmp2-tmp1;
c[now][to]=tmp2-tmp1;
}
}
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;i++) scanf("%d",&a[i]);
for(int i=1;i<n;i++)
{
int x,y;
scanf("%d%d",&x,&y);
graph[x].push_back(y);
graph[y].push_back(x);
}
dfs1(1,0);
dfs2(1,1);
if(n<=1500)
{
long long ans=0;
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
{
int tmp=lca(i,j);
if(a[i]%a[tmp]==0&&a[j]%a[tmp]==0)
ans++;
}
printf("%lld\n",ans);
return 0;
}
long long ans=0;
for(int i=1;i<=n;i++)
{
for(int j=1;j*j<=a[rep[i]];j++)
{
if(j*j==a[rep[i]])
{
sum[j].push_back(i);
break;
}
if(a[rep[i]]%j==0)
{
sum[j].push_back(i);
sum[a[rep[i]]/j].push_back(i);
}
}
}
dfs3(1);
for(int i=1;i<=n;i++)
{
for(auto to:graph[i])
{
auto tmp=c[i][to];
ans+=tmp*(b[i]-tmp-1);
}
ans+=b[i]*2-1;
}
printf("%lld\n",ans);
}