Solution
计算每个质因子在哪些点出现,然后在树上只保存这些点,通过计算大于
0
0
0的
g
(
i
,
j
)
g(i,j)
g(i,j)个数来计算贡献
如果质因子次数
>
1
>1
>1,那么把
p
2
p^2
p2,
p
3
p^3
p3,…,
p
k
p^k
pk都按同样方法做一遍
复杂度
O
(
(
n
+
a
i
)
l
o
g
a
i
)
O((n+a_i)loga_i)
O((n+ai)logai)
Code
代码中*q就相当于 q [ 0 ] q[0] q[0],*vis,*vis1同理
#include<bits/stdc++.h>
using namespace std;
#define fi first
#define se second
typedef pair<int,int> pi;
const int N=100002,M=1e9+7,P=200002;
struct node{
int to,ne;
}e[P<<1];
int a[P],b[P],cnt,tot,ans,vis[P],vis1[P],q[P],h[P],n,i,x,y,num,j,p,t,k;
vector<int>d[N],v[N][17];
bool fl[N];
inline char gc(){
static char buf[100000],*p1=buf,*p2=buf;
return p1==p2&&(p2=(p1=buf)+fread(buf,1,100000,stdin),p1==p2)?EOF:*p1++;
}
inline int rd(){
int x=0,fl=1;char ch=gc();
for(;ch<48||ch>57;ch=gc())if(ch=='-')fl=-1;
for(;48<=ch&&ch<=57;ch=gc())x=(x<<3)+(x<<1)+(ch^48);
return x*fl;
}
pi dfs(int u,int fa){
vis1[u]=*vis1;
pi res(b[u]>0,b[u]==0);
for (int i=h[u],v;i;i=e[i].ne)
if ((v=e[i].to)!=fa && vis[v]==*vis){
pi sub=dfs(v,u);
if (b[u]) sub.fi+=sub.se,sub.se=0;
tot+=res.fi*sub.fi+res.fi*sub.se+res.se*sub.fi;
res.fi+=sub.fi,res.se+=sub.se;
}
return res;
}
int pw(int x,int y){
int z=1;
for (;y;y>>=1,x=1ll*x*x%M)
if (y&1) z=1ll*z*x%M;
return z;
}
void add(int x,int y){e[++tot]=(node){y,h[x]},h[x]=tot;}
int main(){
n=rd();
for (i=1;i<n;i++) x=rd(),y=rd(),add(x,y),add(y,x);
for (i=1;i<=n;i++) a[i]=rd();
for (i=1;i<=n;i++) b[i]=rd();
for (i=2;i<N;i++)
if (!fl[i]){
d[i].push_back(i);//i也是i的约数,不能忘记
for (j=i<<1;j<N;j+=i) fl[j]=1,d[j].push_back(i);
}
ans=1;
for (i=1;i<=n;i++){
if (b[i]) ans=1ll*ans*a[i]%M;
for (j=0;j<d[a[i]].size();j++){
p=d[a[i]][j];
for (t=a[i],cnt=0;t%p==0;t/=p,cnt++) v[p][cnt].push_back(i);
}
}
for (i=2;i<N;i++) if (!fl[i]){
p=i;
for (t=N-1,cnt=0;t;t/=p,cnt++);
tot=0;
for (j=0;j<cnt-1;j++) if (v[i][j].size()){
++*vis,++*vis1,*q=0;
for (k=0;k<v[i][j].size();k++) vis[q[++*q]=v[i][j][k]]=*vis;
for (k=1;k<=*q;k++)
if (vis1[q[k]]!=*vis1) dfs(q[k],0);
}
ans=1ll*ans*pw(i,tot)%M;
}
printf("%d",ans);
}