Live2d Test Env

CF1076E:Vasya and a Tree(DFS&差分)

Vasya has a tree consisting of

Let

Vasya needs you to process

Report to Vasya all values, written on vertices of the tree after processing all queries.

Input

The first line contains single integer

Each of next

Next line contains single integer

Each of next

Output

Print

Examples
Input
5
1 2
1 3
2 4
2 5
3
1 1 1
2 0 10
4 10 100
Output
1 11 1 100 0 
Input
5
2 3
2 1
5 4
3 4
5
2 0 4
3 10 1
1 2 3
2 3 10
1 1 7
Output
10 24 14 11 11 
Note

In the first exapmle initial values in vertices are

 

题意:给定一棵大小为N个树,Q次操作,每次给出三元组(u,d,x)表示给u为根的子树,距离u不超过d的点加值x。

思路:对于每个操作,我们在u处加x,在dep[u+d+1]处减去x。只需要传递一个数组,代表在深度为多少的时候减去多少即可,由于是DFS,满足操作都是在子树里的。

#include<bits/stdc++.h>
#define rep(i,a,b) for(int i=a;i<=b;i++)
#define ll long long
using namespace std;
const int maxn=1000010;
int dep[maxn],N,Laxt[maxn],Next[maxn],To[maxn],cnt;
int laxt2[maxn],next2[maxn],D[maxn],X[maxn],tot; ll ans[maxn];
void add(int u,int v){
    Next[++cnt]=Laxt[u]; Laxt[u]=cnt; To[cnt]=v;
}
void add2(int u,int d,int x){
    next2[++tot]=laxt2[u]; laxt2[u]=tot; D[tot]=d; X[tot]=x;
}
void dfs(int u,int f,ll sum,ll *mp)
{
    dep[u]=dep[f]+1; sum-=mp[dep[u]];
    for(int i=laxt2[u];i;i=next2[i]){
        sum+=X[i];if(dep[u]+D[i]+1<=N) mp[dep[u]+D[i]+1]+=X[i];
    }
    ans[u]=sum;
    for(int i=Laxt[u];i;i=Next[i])
      if(To[i]!=f) dfs(To[i],u,sum,mp);
    for(int i=laxt2[u];i;i=next2[i]){
        sum-=X[i];if(dep[u]+D[i]+1<=N) mp[dep[u]+D[i]+1]-=X[i];
    }
}
ll mp[maxn];
int main()
{
    int u,v,x,Q; scanf("%d",&N);
    rep(i,1,N-1) {
        scanf("%d%d",&u,&v);
        add(u,v); add(v,u);
    }
    scanf("%d",&Q);
    rep(i,1,Q) {
        scanf("%d%d%d",&u,&v,&x);
        add2(u,v,x);
    }

    dfs(1,0,0LL,mp);
    rep(i,1,N) printf("%lld ",ans[i]);
    return 0;
}

 

posted @ 2018-11-30 11:40  nimphy  阅读(275)  评论(0编辑  收藏  举报