zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    【邀请函】小投入 大产出—微软智能云(Azure)之CDN 专题
    Azure镜像市场再下一城,中标软件入驻开启Azure国产操作系统时代
    15分钟完成基于Azure公有云搭建远程测试环境
    独家秘笈!教你解锁移动应用新技能
    “剁手节”来了,红包你抢到了吗?
    Azure 11 月新公布
    面对故宫万千珍宝,升哲科技如何做到“朕知道了”
    高斯-克吕格投影
    cad定制快捷键
    matlab之scatter3()与plot3()函数
  • 原文地址:https://www.cnblogs.com/hua-dong/p/10043266.html
Copyright © 2011-2022 走看看