显示代码纯文本
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<vector>
#include<cmath>
using namespace std;
typedef long long LL;
const LL MOD=1000000007;
const int SIZEN=100010;
int N;
vector<int> c[SIZEN];
int p[SIZEN]={0};
LL w[SIZEN]={0};
LL s[SIZEN]={0},sqr[SIZEN]={0};//s:i子树权值和,sqr:s[i]^2
LL ans=0;
LL realmod(LL x){
x%=MOD;
if(x<0) x+=MOD;
return x;
}
void DFS(int x){
s[x]=sqr[x]=0;
for(int i=0;i<c[x].size();i++){
int u=c[x][i];
DFS(u);
s[x]=realmod(s[x]+s[u]);
sqr[x]=realmod(sqr[x]-sqr[u]);
}
sqr[x]=realmod(sqr[x]+s[x]*s[x]);
ans=realmod(ans+sqr[x]*w[x]);
ans=realmod(ans+realmod(realmod(s[x]*2)*realmod(w[x]*w[x])));
ans=realmod(ans+realmod(w[x]*realmod(w[x]*w[x])));
s[x]=realmod(s[x]+w[x]);
sqr[x]=realmod(s[x]*s[x]);
}
void read(void){
scanf("%d",&N);
scanf("%lld",&w[1]);
for(int i=2;i<=N;i++){
scanf("%d",&p[i]);
c[p[i]].push_back(i);
scanf("%lld",&w[i]);
}
}
int main(){
freopen("asm_algo.in","r",stdin);
freopen("asm_algo.out","w",stdout);
read();
DFS(1);
printf("%lld\n",ans);
return 0;
}