Off white cow month season 12 H Hua Hua and trees month

Topic links:

 

Meaning of the questions: There are three operating

Action 1: represents a node i grow a new son node, right value is 0, the maximum number is the current number +1 (can also be understood as the current operation is the first of several 1, number is the number of new nodes).
Operation 2: represents huahua do the task on the line i of the sub-tree nodes of all the nodes (i.e., it and its descendants all nodes) sum the weights a.
Inquiry 3: huahua need weights given node i at this time.

 

solution:

The entire tree offline

First the tree for this DFS, a subtree node is continuous, when the weight value is directly the whole subtree plus the weight pieces can, can later add a new empty weight-point value.

When the operation is 1, the value of the right to clear this point

2. When operating, all the weights of the nodes of the subtree of this node plus a i

3, when the operation, the weight of the query node i

DFN [i] records the position of point i on the tree in the array, sz [i] is the size of the subtree of node i

#include <bits/stdc++.h>
using namespace std;
const int M = 4e5 + 10;
int cnt, tot, n;
struct Edge{
    int next, to;
}edge[M * 2];
struct node{
    int opt, pos, x;
}a[M];
int dfn[M], sz[M], head[M], bit[M];
void add_egde(int u, int v) {
    //printf("u  %d v %d\n", u, v);
    edge[++tot].next = head[u];
    edge[tot].to = v;
    head[u] = tot;
}
int dfs(int u, int fa) {
    dfn[u] = ++cnt;
    sz[u] = 1;
    for(int i = head[u]; i; i = edge[i].next) {
        int v = edge[i].to;
        if(v == fa) continue;
        sz[u] += dfs(v, u);
    }
    return sz[u];
}
void update(int i, int x) {
    while(i <= n + 1) {
        bit[i] += x;
        i += i & (-i);
    }
}
void add(int l, int r, int val) {
    update(l, val);
    update(r + 1, -val);
}
int query(int i) {
    int ans = 0;
    while(i) {
        ans += bit[i];
        i -= i & (-i);
    }
    return ans;
}
int main(){
    int m;
    scanf("%d", &m);
    for(int i = 1; i <= m; i++) {
        scanf("%d%d", &a[i].opt, &a[i].pos);
        if(a[i].opt == 1) add_egde(a[i].pos, ++n), a[i].pos = n;
        if(a[i].opt == 2) scanf("%d", &a[i].x);
    }
    dfs(0, -1);
    for(int i = 1; i <= m; i++) {
        if(a[i].opt == 1) {
            int u = a[i].pos;
            int val = query(dfn[u]);
            add(dfn[u], dfn[u], -val);
        }
        else if(a[i].opt == 2) {
            int u = a[i].pos;
            int val = a[i].x;
            add(dfn[u], dfn[u] + sz[u] - 1, val);
        }
        else printf("%d\n", query(dfn[a[i].pos]));
    }
    return 0;
}
View Code

 

 

 

Guess you like

Origin www.cnblogs.com/linglinga/p/12031206.html
Recommended