1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
| #include<bits/stdc++.h> using namespace std; const int maxn=5e5; const int maxm=2e7; const int inf=2e9; const int mod=1e9+7; int n; int a[maxn+5],b[maxn+5]; vector<int> E[maxn+5]; int c[maxn+5]; int rt[maxn+5],tot; int ls[maxm+5],rs[maxm+5]; int ans[maxm+5],cnt[maxm+5],sum[maxm+5]; int res[maxn+5]; short wst[15],wtp; inline int Read(){ char ch=getchar(); while(ch<'0'||'9'<ch) ch=getchar(); int res=0; while('0'<=ch&&ch<='9') res=(res<<1)+(res<<3)+ch-'0',ch=getchar(); return res; } inline void Write(int x){ if(!x){puts("0");return;} while(x) wst[++wtp]=x%10,x/=10; while(wtp) putchar('0'+wst[wtp--]); putchar('\n'); } inline void Pushup(int x){ ans[x]=(ans[ls[x]]+ans[rs[x]]+1ll*cnt[ls[x]]*sum[rs[x]]%mod-1ll*cnt[rs[x]]*sum[ls[x]]%mod)%mod; sum[x]=(sum[ls[x]]+sum[rs[x]])%mod; cnt[x]=(cnt[ls[x]]+cnt[rs[x]])%mod; } void Modify(int &x,int L,int R,int p){ if(!x) x=++tot,ls[x]=rs[x]=ans[x]=cnt[x]=sum[x]=0; if(L==R) cnt[x]++,sum[x]=(sum[x]+p%mod)%mod; else{ int mid=(R-L)/2+L; if(p<=mid) Modify(ls[x],L,mid,p); else Modify(rs[x],mid+1,R,p); Pushup(x); } } void Merge(int &x,int y,int L,int R){ if(!x) x=y; else if(!y) return; else if(L==R){ cnt[x]=(cnt[x]+cnt[y])%mod; sum[x]=(sum[x]+sum[y])%mod; } else{ int mid=(R-L)/2+L; Merge(ls[x],ls[y],L,mid); Merge(rs[x],rs[y],mid+1,R); Pushup(x); } } void Dfs(int u,int fa,int ng){ Modify(rt[u]=0,1,inf,c[u]); for(int v:E[u]){ if(v==fa) continue; Dfs(v,u,ng); Merge(rt[u],rt[v],1,inf); } res[u]=(res[u]+ng*ans[rt[u]])%mod; } signed main(){ freopen("distance.in","r",stdin); freopen("distance.out","w",stdout); int u,v; n=Read(); for(int i=1;i<n;i++){ u=Read(),v=Read(); E[u].push_back(v); E[v].push_back(u); } for(int i=1;i<=n;i++) a[i]=Read(),b[i]=Read(); for(int i=1;i<=n;i++) c[i]=2*a[i]; tot=0;Dfs(1,0,1); for(int i=1;i<=n;i++) c[i]=2*b[i]; tot=0;Dfs(1,0,1); for(int i=1;i<=n;i++) c[i]=a[i]+b[i]; tot=0;Dfs(1,0,-1); for(int i=1;i<=n;i++) c[i]=a[i]-b[i]+1e9; tot=0;Dfs(1,0,-1); for(int i=1;i<=n;i++) Write((res[i]+mod)%mod); return 0; }
|