https://codeforces.com/problemset/problem/1076/E
大致题意:
给n个节点的树,m次操作给x,y,z,以x为父节点向下深度差小于等于y的点都加上权值z。
树上差分—深度差分
按深度差分。通过离线实现
1.记录所有的修改、
2.深搜每个节点,并且打上差分标记
3,算答案后应回溯(该差分是从根部开始处理) 。
/*
cf1076E
树上差分—深度差分
https://codeforces.com/problemset/problem/1076/E
按深度差分。通过离线实现
1.记录所有的修改、
2.深搜每个节点,并且打上差分标记
3,算答案后应回溯(该差分是从根部开始处理)
*/
#include <bits/stdc++.h>
using namespace std;
#define int long long
const int N=300005;
vector<int>v[N];
vector<pair<int,int>>vc[N];
int ans[N];
int depth[N];
int mark[N];//每个点的差分值
int sum=0,n;
void dfs(int son,int father){
depth[son]=depth[father]+1;//每个深度记录
for(int i=0;i<vc[son].size();i++){
mark[depth[son]]=mark[depth[son]]+vc[son][i].second;//在这条连的该深度打上差分标记
if(depth[son]+vc[son][i].first+1<=n)//防止越界
mark[depth[son]+vc[son][i].first+1]-=vc[son][i].second;//在下界打上结束的差分标记
}
sum+=mark[depth[son]];ans[son]=sum;//这时候的sum(从根部加到改点)加上mark就是该点的值
for(int i=0;i<v[son].size();i++){
if(v[son][i]!=father){
dfs(v[son][i],son);//将该条链搜到底
}
}
sum-=mark[depth[son]];//回溯时减去前条链计算的差分值
for(int i=0;i<vc[son].size();i++){//同理
mark[depth[son]]=mark[depth[son]]-vc[son][i].second;
if(depth[son]+vc[son][i].first+1<=n)
mark[depth[son]+vc[son][i].first+1]+=vc[son][i].second;
}
}
signed main(){
scanf("%lld",&n);
for(int i=1;i<n;i++){
int x,y;
scanf("%lld%lld",&x,&y);
v[x].push_back(y);
v[y].push_back(x);
}int m;scanf("%lld",&m);
for(int i=1;i<=m;i++){
int x,y,z;
scanf("%lld%lld%lld",&x,&y,&z);
vc[x].push_back(make_pair(y,z));
}
dfs(1,0);
for(int i=1;i<=n;i++)
printf("%lld ",ans[i]);
return 0;
}