Tree array maintains subtree and

Title link

Problem

\ (It is known that there are n nodes with n−1 edges, forming a tree structure \) .

\ (Given a root node k, each node has a weight, and the weight of node i is vi \)

\ (For m operations, there are two types of operations: \)

\ (1 \ space a \ space x: means to add the weight of node a to x \)

\ (2 \ space a: means sum of all nodes in the subtree of node a (including node a itself) \)

Solution

\ (There is a conclusion: the timestamp dfn of a node and all its subtree nodes is continuous \)

\ (We use a dfn timestamp, time1 when entering, time2 \ after traversing all the subtree nodes)

\ (Then the range of this node and all its sub-tree nodes is a continuous time1-time2, then you can use the tree array to maintain \)

\ (That is, through dfn time stamp (dfs order), convert the tree into a continuous linear segment \)

#include<bits/stdc++.h>
#define IOS ios::sync_with_stdio(0); cin.tie(0);
using namespace std;
typedef long long ll;
const int maxn = 1e6+10;
ll val[maxn];
ll valu[maxn];
vector<int>E[maxn];
int dfn[maxn],ed[maxn];
int cnt;
int n,m,k;
int lowbit(int x){
    return x&-x;
}
void add(int x,ll w){
    while(x<=n){
        val[x] += w;
        x += lowbit(x);
    }
}
ll query(int x){
    ll res = 0;
    while(x){
        res += val[x];
        x -= lowbit(x);
    }
    return res;
}
void dfs(int p,int fa){
    dfn[p] = cnt++; add(dfn[p],valu[p]);
    for(int i=0;i<(int)E[p].size();i++){
        int v = E[p][i];
        if(v!=fa){
            dfs(v,p);
        }
    }
    ed[p] = cnt-1;
}
int main(){
    IOS
    cin>>n>>m>>k;
    for(int i=1;i<=n;i++) cin>>valu[i];
    for(int i=1;i<n;i++){
        int u,v;
        cin>>u>>v;
        E[u].push_back(v);
        E[v].push_back(u);
    }
    cnt = 1;
    dfs(k,0);
    for(int i=1;i<=m;i++){
        int op,p;
        cin>>op>>p;
        if(op==1){
            ll w;
            cin>>w;
            add(dfn[p],w);
        }else{
            cout<<query(ed[p])-query(dfn[p]-1)<<endl;
        }
    }
    return 0;
}

Guess you like

Origin www.cnblogs.com/Tianwell/p/12733086.html