显示代码纯文本
#include <iostream>
#include <cstdio>
using namespace std;
typedef long long LL;
const int maxn = 1e5 + 10;
const int lcy = 1e9 + 7;
struct Edge {
int to, ne;
Edge() {}
Edge(int to_, int ne_) { to = to_, ne = ne_; }
} e[maxn << 1];
int head[maxn], ecnt;
void add_edge(int fr, int to) {
e[++ecnt] = Edge(to, head[fr]), head[fr] = ecnt;
}
#define is_num(x) (x <= '9' and x >= '0')
inline int get_num() {
char tmp = getchar();
int res = 0;
while (not is_num(tmp)) tmp = getchar();
while ( is_num(tmp)) {
res = (res << 3) + (res << 1) + tmp - '0';
tmp = getchar();
}
return res;
}
int sum[maxn];
int sz[maxn];
int v[maxn];
int n;
LL ans = 0;
void dfs(int now, int fr) {
sz[now] = 1;
sum[now] = v[now];
for (int i = head[now]; i; i = e[i].ne) {
int to = e[i].to;
if (to == fr) continue;
dfs(to, now);
sum[now] = (sum[now] + sum[to]) % lcy;
sz[now] += sz[to];
}
LL tot_s = sum[now];
LL tmp = 0;
for (int i = head[now]; i; i = e[i].ne) {
int to = e[i].to;
if (to == fr) continue;
tmp = (tmp + (1ll * sum[to] * ((tot_s - sum[to] + lcy) % lcy) % lcy)) % lcy;
tmp = (tmp + (1ll * sum[to] * v[now] % lcy)) % lcy;
}
tmp = (tmp + (1ll * v[now] * v[now] % lcy)) % lcy;
tmp = (1ll * tmp * v[now]) % lcy;
ans = (ans + tmp) % lcy;
}
inline void read() {
n = get_num();
v[1] = get_num();
int fa;
for (int i = 2; i <= n; i++) {
fa = get_num();
v[i] = get_num();
add_edge(fa, i);
}
}
inline void solve() {
dfs(1, 0);
printf("%lld\n", ans);
}
int main() {
freopen("asm_algo.in", "r", stdin);
freopen("asm_algo.out", "w", stdout);
read();
solve();
return 0;
}