题解:P16222 [ECUSTPC 2025] 荷塘月色
P16222 [ECUSTPC 2025] 荷塘月色
Description
给定一棵带点权树,定义一条路径
求出等概率随机选出不同的两点
Solution
考虑枚举
枚举
所以考虑枚举
由于值域是
枚举了当前的
由于
于是需要对
可以容斥,变成导出子图所有路径的计数减去不包含
实现上,可以先记录
先加入所有
然后加入
两者做差就是
时间复杂度
Code
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define rep(a,b,c) for(int a=(b);a<=(c);++a)
#define per(a,b,c) for(int a=(b);a>=(c);--a)
const int N=1e5+5,P=998244353;
ll pw(ll x,ll p=P-2){return p?pw(x*x%P,p>>1)*(p&1?x:1)%P:1;}
int T,n;
int a[N];
vector <int> g[N],nod[N];
ll tot;
int fa[N],sz[N];
pair<int,int> stk[N];
int top;
int find(int x){
while(x!=fa[x]) x=fa[x];
return x;
}
void merge(int u,int v){
u=find(u),v=find(v);
if(u==v) return;
if(sz[u]<sz[v]) swap(u,v);
fa[v]=u;
tot+=1LL*sz[u]*sz[v];
sz[u]+=sz[v];
stk[++top]={u,v};
}
void cut(){
auto [u,v]=stk[top--];
fa[v]=v;
sz[u]-=sz[v];
tot-=1LL*sz[u]*sz[v];
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0),cout.tie(0);
cin>>T;
while(T--){
cin>>n;
rep(i,1,n) g[i].clear(),nod[i].clear(),fa[i]=i,sz[i]=1;
rep(i,2,n){
int u,v;
cin>>u>>v;
g[u].push_back(v);
g[v].push_back(u);
}
rep(i,1,n) cin>>a[i],nod[a[i]].push_back(i);
ll res=0;
rep(d,1,n){
ll val=0;
for(int i=d*2;i<=n;i+=d) for(int u:nod[i]) for(int v:g[u]) if(a[v]%d==0&&a[v]>d) merge(u,v);
val-=tot;
for(int u:nod[d]) for(int v:g[u]) if(a[v]%d==0) merge(u,v);
val+=tot;
res+=val*d;
while(top) cut();
}
res=res*2%P*pw(n)%P*pw(n-1)%P;
cout<<res<<'\n';
}
return 0;
}