求和

求和

https://ac.nowcoder.com/acm/problem/204871

求和

利用dfs序在子树上的连续性,然后通过单点修改,区间查询即可,这点只要用一颗树状数组即可完成。

/*
  Author : lifehappy
*/
#include <bits/stdc++.h>

using namespace std;

typedef long long ll;

const int N = 1e6 + 10;

ll tree[N];

int head[N], to[N << 1], nex[N << 1], cnt = 1;

int l[N], r[N], rk[N], value[N], n, m, k, tot;

void add(int x, int y) {
    to[cnt] = y;
    nex[cnt] = head[x];
    head[x] = cnt++;
}

void dfs(int rt, int fa) {
    l[rt] = ++tot, rk[tot] = rt;
    for(int i = head[rt]; i; i = nex[i]) {
        if(to[i] == fa) continue;
        dfs(to[i], rt);
    }
    r[rt] = tot;
}

int lowbit(int x) {
    return (-x) & x;
}

void update(int x, int value) {
    while(x <= n) {
        tree[x] += value;
        x += lowbit(x);
    }
}

ll query(int x) {
    ll ans = 0;
    while(x) {
        ans += tree[x];
        x -= lowbit(x);
    }
    return ans;
}

int main() {
    // freopen("in.txt", "r", stdin);
    // freopen("out.txt", "w", stdout);
    // ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
    scanf("%d %d %d", &n, &m, &k);
    for(int i = 1; i <= n; i++) {
        scanf("%lld", &value[i]);
    }
    for(int i = 1; i < n; i++) {
        int x, y;
        scanf("%d %d", &x, &y);
        add(x, y);
        add(y, x);
    }
    dfs(k, 0);
    for(int i = 1; i <= n; i++) {
        update(l[i], value[i]);
    }
    for(int i = 1; i <= m; i++) {
        int op;
        scanf("%d", &op);
        if(op == 1) {
            int a, x;
            scanf("%d %d", &a, &x);
            update(l[a], x);
        }
        else {
            int a;
            scanf("%d", &a);
            printf("%lld\n", query(r[a]) - query(l[a] - 1));
        }
    }
    return 0;
}
全部评论

相关推荐

白火同学:1、简历可以浓缩成一页,简历简历先要“简”方便HR快速过滤出有效信息,再要“历”用有效信息突出个人的含金量。 2、教育背景少了入学时间~毕业时间,HR判断不出你是否为应届生。 3、如果你的平台账号效果还不错,可以把账号超链接或者用户名贴到对应位置,一是方便HR知道你是具体做了什么内容的运营,看到账号一目了然,二是口说无凭,账号为证,这更有说服力。
面试被问期望薪资时该如何...
点赞 评论 收藏
分享
评论
4
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务