显示代码纯文本
#include<bits/stdc++.h>
#define int long long
using namespace std;
ifstream fin("asm_algo.in");
ofstream fout("asm_algo.out");
auto mread = [](){
int x;
fin >> x;
return x;
};
const int N = 1e5 + 5, MOD = 1e9 + 7;
int n = mread(), a[N], p[N], ans, s[N];
vector<int> v[N];
void dfs(int x){
int sum = 0;
for(int y : v[x]){
dfs(y);
(s[x] += s[y]) %= MOD;
}
if(s[x] > 0){
for(int y : v[x]){
(sum += s[y] * (s[x] - s[y]) % MOD) %= MOD;
}
(ans += sum * a[x] % MOD) %= MOD;
}
(ans += a[x] * a[x] % MOD * a[x] % MOD) %= MOD;
(ans += a[x] * s[x] % MOD * a[x] % MOD * 2 % MOD) %= MOD;
(s[x] += a[x]) %= MOD;
return;
}
signed main(){
a[1] = mread();
for(int i = 2; i <= n; i ++){
p[i] = mread(), a[i] = mread();
v[p[i]].push_back(i);
}
dfs(1);
fout << ans;
return 0;
}