题目大意:一棵树,每次操作使得u,v间的路径上所有点权重加w,问最后每个点的权重
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;
const int maxn = 5e4 + 10;
#define lson o * 2
#define rson o * 2 + 1
int n, Q, T, cur;
int sum[maxn<<2], lazy[maxn<<2]; //线段树相关
int p[maxn], hcnum[maxn], depth[maxn], hson[maxn], sz[maxn], cnt[maxn];
//p[i]为节点i的父节点, hcnum[i]为节点i所在重链中最上面的节点, depth[i]为节点i的深度
//hson[i]为节点i的重儿子, sz[i]为以i为子树的节点个数, cnt[i]为节点i在线段树中的序号
vector<int> G[maxn]; //存储图
void dfs1(int u, int fa) { //第一次dfs, 得到每个节点的重儿子, 深度, 和父节点
sz[u] = 1;
p[u] = fa;
hson[u] = 0;
depth[u] = depth[fa] + 1;
for (int i = 0; i < G[u].size(); i++) {
int v = G[u][i];
if (v == fa) continue;
dfs1(v, u);
sz[u] += sz[v];
if (sz[v] > sz[hson[u]]) hson[u] = v; //重儿子为节点最多的儿子
}
}
void dfs2(int u, int fa, int x) { //第二次dfs, 得到每个节点在线段树中的标号及所属重链的标号
cur++;
cnt[u] = cur;
hcnum[u] = x; //重链的标号为该重链最顶端的节点
if (hson[u]) dfs2(hson[u], u, x); //先处理重链,保证剖分完之后每条链中的标号是连续的
for (int i = 0; i < G[u].size(); i++) {
int v = G[u][i];
if (v == fa || v == hson[u]) continue;
dfs2(v, u, v);
}
}
void pushdown(int o, int l, int r) {
if (lazy[o]) {
int mid = (l + r) / 2;
lazy[lson] += lazy[o];
lazy[rson] += lazy[o];
sum[lson] += lazy[o] * (mid - l + 1);
sum[rson] += lazy[o] * (r - mid);
lazy[o] = 0;
}
}
void update(int o, int l, int r, int L, int R, int x) {
if (L <= l && r <= R) {
lazy[o] += x;
sum[o] += (r - l + 1) * x;
return;
}
pushdown(o, l, r);
int mid = (l + r) / 2;
if (L <= mid) update(lson, l, mid, L, R, x);
if (R > mid) update(rson, mid + 1, r, L, R, x);
sum[o] = sum[lson] + sum[rson];
}
int query(int o, int l, int r, int x) {
if (l == r) return sum[o];
pushdown(o, l, r);
int mid = (l + r) / 2;
if (x <= mid) return query(lson, l, mid, x);
else return query(rson, mid + 1, r, x);
}
void solve(int u, int v, int w) {
while (hcnum[u] != hcnum[v]) { //直到两点位于同一条重链才停止
if (depth[hcnum[u]] < depth[hcnum[v]]) swap(u, v);
update(1, 1, n, cnt[hcnum[u]], cnt[u], w); //更新当前区间
u = p[hcnum[u]];
}
if (depth[u] < depth[v]) swap(u, v);
update(1, 1, n, cnt[v], cnt[u], w);
}
int main() {
scanf("%d", &T);
int cas = 0;
while (T--) {
cas ++;
scanf("%d", &n);
for (int i = 1; i <= n; i++) G[i].clear();
memset(sum, 0, sizeof(sum));
memset(lazy, 0, sizeof(lazy));
int u, v, w;
sz[0] = cur = 0;
depth[1] = -1;
for (int i = 1; i < n; i++) {
scanf("%d%d", &u, &v);
u++; v++;
G[u].push_back(v);
G[v].push_back(u);
}
dfs1(1, 1);
dfs2(1, 1, 1);
scanf("%d", &Q);
for (int i = 0; i < Q; i++) {
scanf("%d%d%d", &u, &v, &w);
u++; v++;
solve(u, v, w);
}
printf("Case #%d:\n", cas);
for (int i = 1; i <= n; i++) printf("%d\n", query(1, 1, n, cnt[i]));
}
return 0;
}