DFS order 1

To a rooted tree, the tree by the number of N nodes 1..N composition. The root of the number R.
Each node has a weight, the weight value of node i vi.
Then there are M groups of operations, operations are divided into two categories:
. 1 AX, a node represents the right to increase the value of X;
2 a, a value representing a sum of the weights of the nodes find all the sub-tree nodes and.
Input format
The first line contains three integers N, M and R.
The second line has N integers, the i-th integer vi.
N-1 in the next row, two rows each integers, indicates that an edge.
In the next M rows, each row a set of operations.
Output format
for each operation of a 2, outputs an integer representing the "node in a subtree rooted at" the weighted values of all nodes and.
Sample
Sample Input 1
10 14. 9
12-6-4-3128966 2
. 8 2
2 10
. 8. 6
2. 7
. 7. 1
. 6. 3
10. 9
2. 4
10. 5
. 1. 4 -1
2 2
. 1. 7 -1
2 10
. 1. 5 10
2. 1
. 1. 7 -5
2. 5
. 1. 1. 8
2. 7
. 1. 8. 8
2 2
. 1. 5. 5
26
Sample Output 1

21
34
12
12
23
31
4
1<=N,M<=10^6,1<=R<=N
-10^6<=vi,x<=10^6

#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 6;
typedef long long ll;
ll c[maxn], in[maxn], out[maxn], tot, d[maxn], head[maxn], cnt, n, m, r;
struct node {
    int to, nxt;
} e[maxn << 1];
void addedge(int u, int v) {
    e[++tot] = { v, head[u] };
    head[u] = tot;
}
void dfs(int u) {
    in[u] = ++cnt;
    for (int i = head[u]; i; i = e[i].nxt) {
        int v = e[i].to;
        if (in[v])
            continue;
        dfs(v);
    }
    out[u] = cnt;
}
ll lowbit(int x) 
{ 
	return x & -x; 
}
void add(int u, int x) 
{
    while (u <= n) 
	{
        c[u] += x;
        u += lowbit(u);
    }
}
ll query(int u) {
    ll ret = 0;
    while (u > 0) {
        ret += c[u];
        u -= lowbit(u);
    }
    return ret;
}
int main() {
    cin >> n >> m >> r;
    for (int i = 1; i <= n; ++i) cin >> d[i];
    for (int i = 1, a, b; i < n; ++i) 
	{
        cin >> a >> b;
        addedge(a, b), addedge(b, a);
    }
    dfs(r);
    for (int i = 1; i <= n; ++i) //最始权值 
	    add(in[i], d[i]);
    for (int i = 1, op, a, x; i <= m; ++i) 
	{
        cin >> op >> a;
        if (op == 2) 
		{
            cout << query(out[a]) - query(in[a] - 1) << endl;
        } 
		else 
		{
            cin >> x;
            add(in[a], x);
        }
    }
}

  

Guess you like

Origin www.cnblogs.com/cutemush/p/11795063.html