解题思路:
感觉自己当时好菜啊……
设 fu,i f u , i 为 u u 选 的概率,假如是从左子树转移来的,则
fu,i=fl,i(p∑fr,j<i+(1−p)∑fr,j>i)
f
u
,
i
=
f
l
,
i
(
p
∑
f
r
,
j
<
i
+
(
1
−
p
)
∑
f
r
,
j
>
i
)
然后想到线段树合并,节点表示选当前区间的概率和就可以方便地合并了,合并到一棵子树时打乘积标记下传即可。
#include<iostream>
#include<algorithm>
#define ll long long
#define pb push_back
using namespace std;
ll getint()
{
ll i=0,f=1;char c;
for(c=getchar();(c!='-')&&(c<'0'||c>'9');c=getchar());
if(c=='-')c=getchar(),f=-1;
for(;c>='0'&&c<='9';c=getchar())i=(i<<3)+(i<<1)+c-'0';
return i*f;
}
const int N=300005,M=6000005,mod=998244353,inv=796898467;
int n,m,son[N][2];ll p,w[N],b[N];
int tot,rt[N],lc[M],rc[M];ll ans,s[M],tag[M];
void mul(int x,ll v){s[x]=s[x]*v%mod,tag[x]=tag[x]*v%mod;}
void pushdown(int x){if(tag[x]!=1)mul(lc[x],tag[x]),mul(rc[x],tag[x]),tag[x]=1;}
void insert(int &x,int l,int r,int v)
{
if(!x)x=++tot,s[x]=tag[x]=1;
if(l==r)return;
int mid=l+r>>1;
if(v<=mid)insert(lc[x],l,mid,v);
else insert(rc[x],mid+1,r,v);
}
int merge(int x,int y,ll sx,ll sy)
{
if(!y){mul(x,sy);return x;}
if(!x){mul(y,sx);return y;}
pushdown(x),pushdown(y);
ll x0=s[lc[x]],x1=s[rc[x]],y0=s[lc[y]],y1=s[rc[y]];
lc[x]=merge(lc[x],lc[y],(sx+(1+mod-p)*x1)%mod,(sy+(1+mod-p)*y1)%mod);
rc[x]=merge(rc[x],rc[y],(sx+p*x0)%mod,(sy+p*y0)%mod);
s[x]=(s[lc[x]]+s[rc[x]])%mod;
return x;
}
int solve(int x)
{
if(!son[x][0])
{
insert(rt[x],1,m,lower_bound(b+1,b+m+1,w[x])-b);
return rt[x];
}
int l=solve(son[x][0]);
if(!son[x][1])return l;
int r=solve(son[x][1]);
p=w[x];
return merge(l,r,0,0);
}
ll calc(int x,int l,int r)
{
if(l==r){return (ll)l*b[l]%mod*s[x]%mod*s[x]%mod;}
pushdown(x);
int mid=l+r>>1;
return (calc(lc[x],l,mid)+calc(rc[x],mid+1,r))%mod;
}
int main()
{
//freopen("lx.in","r",stdin);
n=getint();
for(int i=1,x;i<=n;i++)x=getint(),son[x][son[x][0]?1:0]=i;
for(int i=1;i<=n;i++)
{
w[i]=getint();
son[i][0]?w[i]=w[i]*inv%mod:b[++m]=w[i];
}
sort(b+1,b+m+1);
cout<<calc(solve(1),1,m)<<'\n';
}