Propagating tree

题目地址:

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

基本思路:

我们发现是非常裸的子树修改然后单点查询,
所以我们考虑用差分树状数组去维护子树状态,
但是我们发现它对于权值的修改是一层加一层减这样的,
所以一个树状数组肯定不够了,我们考虑维护两个树状数组,
一个维护奇数层的修改,一个维护偶数层的修改,
这样每次我们对同奇/偶的层加,对不同奇/偶的层减,就能完成对子树的维护,
然后对于每次查询,判断是奇层还是偶层加上贡献就行了。

参考代码:

#include <bits/stdc++.h>
using namespace std;
#define IO std::ios::sync_with_stdio(false); cin.tie(0)
#define ll long long
#define ull unsigned long long
#define SZ(x) ((int)(x).size())
#define all(x) (x).begin(), (x).end()
#define rep(i, l, r) for (int i = l; i <= r; i++)
#define per(i, l, r) for (int i = l; i >= r; i--)
#define mset(s, _) memset(s, _, sizeof(s))
#define pb push_back
#define pii pair <int, int>
#define mp(a, b) make_pair(a, b)
#define debug(x) cerr << #x << " = " << x << '\n';
#define pll pair <ll, ll>
#define fir first
#define sec second
#define INF 0x3f3f3f3f
#define int ll

inline int read() {
  int x = 0, neg = 1; char op = getchar();
  while (!isdigit(op)) { if (op == '-') neg = -1; op = getchar(); }
  while (isdigit(op)) { x = 10 * x + op - '0'; op = getchar(); }
  return neg * x;
}
inline void print(int x) {
  if (x < 0) { putchar('-'); x = -x; }
  if (x >= 10) print(x / 10);
  putchar(x % 10 + '0');
}

const int maxn = 2e5 + 10;
struct BIT{
    int t[maxn << 2];
    int lowbit(int x){
      return x & (-x);
    }
    void clear(){
      memset(t,0,sizeof(t));
    }
    int sum(int x){
      int res = 0;
      while(x){
        res += t[x];
        x -= lowbit(x);
      }
      return res;
    }
    void update(int x,int v){
      while(x < maxn){
        t[x] += v;
        x += lowbit(x);
      }
    }
}bit1,bit2; // 1 奇数层, 2 偶数层;
vector<int> G[maxn];
int n,m,w[maxn],l[maxn],r[maxn],dep[maxn];
signed main() {
  n = read(), m = read();
  rep(i, 1, n) w[i] = read();
  rep(i, 1, n - 1) {
    int u = read(), v = read();
    G[u].push_back(v);
    G[v].push_back(u);
  }
  int dfn = 0;
  function<void(int, int, int)> dfs = [&](int u, int par, int d) {
      l[u] = ++dfn;
      dep[u] = d;
      for (auto to : G[u]) {
        if (to == par) continue;
        dfs(to, u, d + 1);
      }
      r[u] = dfn;
  };
  dfs(1, 0, 1);
  rep(i, 1, m) {
    int op = read();
    if (op == 1) {
      int x = read(), val = read();
      if (dep[x] & 1) {
        bit1.update(l[x], val);
        bit1.update(r[x] + 1, -val);
        bit2.update(l[x], -val);
        bit2.update(r[x] + 1, val);
      } else {
        bit1.update(l[x], -val);
        bit1.update(r[x] + 1, val);
        bit2.update(l[x], val);
        bit2.update(r[x] + 1, -val);
      }
    } else {
      int x = read();
      int ans = w[x];
      if (dep[x] & 1) ans += bit1.sum(l[x]);
      else ans += bit2.sum(l[x]);
      print(ans); puts("");
    }
  }
  return 0;
}