题解:CF2241E Fair and Square
zhangjizhi_zako
·
·
题解
很好的题,杂揉了各种知识点。
分析
设 b_u 表示从根节点(此题给的是无根树,假设为 1)到点 u 的路径中,所有节点乘起来起来的结果,则 \displaystyle p(u,v)=\frac{b_ub_v}{{b_{ \operatorname{LCA}(u,v)}}{b_{fa[ \operatorname{LCA}(u,v)]}}}。
接着,设 \operatorname{A}(x) 表示 x 除以其最大的 是完全平方数的 因数 得到的值(有点绕),则 \displaystyle \operatorname{A}(p(u,v))=\frac{b_ub_v}{{b_{fa[ \operatorname{LCA}(u,v)]}}^2{a_{ \operatorname{LCA}(u,v)}}}=\operatorname{A}(b_ub_va_{ \operatorname{LCA}(u,v)})。则 \displaystyle \operatorname{A}(p(u,v)p(v,w)p(w,u))=\operatorname{A}(b_u^2b_v^2b_w^2a_{ \operatorname{LCA}(u,v)}a_{ \operatorname{LCA}(v,w)}a_{ \operatorname{LCA}(w,u)})=\operatorname{A}(a_{ \operatorname{LCA}(u,v)}a_{ \operatorname{LCA}(v,w)}a_{ \operatorname{LCA}(w,u)})。
原问题化为:有多少个三元组 (u,v,w),使得 \operatorname{A}(a_{ \operatorname{LCA}(u,v)}a_{ \operatorname{LCA}(v,w)}a_{ \operatorname{LCA}(w,u)})=1。
对于原式,不难发现有两个数的值必然是相同的。钦定 a_{ \operatorname{LCA}(u,v)} 是剩下的那个,则 a_{ \operatorname{LCA}(u,v)} 必然需要为完全平方数才能统计。可以直接枚举 \operatorname{LCA}(u,v) 并分讨 w。
-
-
怎么拆最后一个式子?
至此,此题就做完了。
代码中有注释,可一起食用。
:::success[Code]
```cpp
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N=4e5+10;
int a[N],t,b[N],s[N],ss[N],sss[N];
int h[N],to[N],nxt[N],idx,n,sz[N],ans;
void add(int u,int v)
{
nxt[++idx]=h[u];
to[idx]=v;
h[u]=idx;
}
int check(int x)//判断是否是完全平方数
{
int ava=sqrtl(x);
if(ava*ava==x) return 1;
return 0;
}
void dfs(int u,int fth)
{
int res=0;
sz[u]=1;
int cnt=0;
for(int i=h[u];i;i=nxt[i])
{
int v=to[i];
if(v==fth) continue;
dfs(v,u);
res+=(sz[u]-1)*sz[v];//统计原题解中倒数第二个式子
sz[u]+=sz[v];
}
if(check(a[u]))
{
ans+=res*(n-sz[u]+1);
ans+=(sz[u]-1)*(n-sz[u]);//第一种情况
for(int i=h[u];i;i=nxt[i]) if(to[i]!=fth) b[++cnt]=sz[to[i]];//一定要注意递归结束后再用,不然会被之后覆盖
for(int i=cnt;i>=1;i--)
{
s[i]=s[i+1]+b[i];
}
for(int i=cnt;i>=1;i--)
{
ss[i]=ss[i+1]+b[i]*s[i+1];
}
for(int i=cnt;i>=1;i--)
{
sss[i]=sss[i+1]+b[i]*ss[i+1];
}
ans+=sss[1];//第二种情况
}
for(int i=1;i<=cnt;i++)
{
b[i]=s[i]=ss[i]=sss[i]=0;//归0
}
}
void solve()
{
cin>>n;
for(int i=1;i<=n;i++)
{
cin>>a[i];
}
for(int i=1;i<n;i++)
{
int u,v;
cin>>u>>v;
add(u,v);
add(v,u);
}
dfs(1,0);
cout<<ans<<'\n';
ans=0;
for(int i=1;i<=n;i++) h[i]=sz[i]=0;
for(int i=1;i<=idx;i++) nxt[i]=to[i]=0;
idx=0;//多测清空
}
signed main()
{
cin>>t;
while(t--)
{
solve();
}
}
```
:::