题目链接
这题居然没有想到乘法原理…还是要多想想乘法原理啊…
先dfs出$siz_i$为每个点子树大小。然后对每个边算次数。根据乘法原理,次数为$siz_i \times (n-siz_i)$,那么这条边对答案的贡献为$val \times siz_i \times (n-siz_i)$,然后就可以求了。
注意开long long,而且乘法会溢出所以要在中途每个强制转换
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
#include<queue>
#define ms(i, j) memset(i, j, sizeof i)
#define LL long long
#define db double
using namespace std;
const int MAXN = 100000 + 5;
struct data {int v, w;}ed[MAXN * 2];
int en, n, siz[MAXN], val[MAXN];
vector<int> G[MAXN];
void ins(int x, int y, int c) {
en++, ed[en].v = y, ed[en].w = c, G[x].push_back(en);//边权实际上不需要存,但是这存了就不改了
}
void dfs(int u, int pa) {
siz[u] = 1;
for (int i=0;i<G[u].size();i++) {
data p = ed[G[u][i]];
int v = p.v, w = p.w;
if (v != pa) {
dfs(v, u);
siz[u] += siz[v];
}
}
}
void clean() {
en = 0;
for (int i=0;i<=n;i++) siz[i] = val[i] = 0, G[i].clear();
}
void solve() {
clean();
for (int i=1;i<n;i++) {
int x;
scanf("%d%d", &x, &val[i + 1]);
ins(x, i+1, val[i + 1]);
}
dfs(1, 0);
LL ans = 0;
for (int i=1;i<=n;i++) {
ans += (LL)val[i] * (LL)(n - siz[i]) * (LL)siz[i];//防乘法溢出
}
printf("%lld\n", ans);
int Q; scanf("%d", &Q);
while (Q--) {
int x, y;
scanf("%d%d", &x, &y);
ans += (LL)(y - val[x]) * (LL)(n - siz[x]) * (LL)siz[x];//防乘法溢出
val[x] = y;
printf("%lld\n", ans);
}
}
int main() {
scanf("%d", &n), solve();
return 0;
}