383C - Propagating tree 线段树加时间戳

首先每次处理以一个点为根的所有子树点 就要用时间戳加线段树区间更新
因为每次add一个点,那么加减是交替的,所以线段树存储深度为奇数的点的add值
最后查询如果是偶数 ans = -ans;

#include
#include
#include
#define maxn 200005
#define LL long long
#define lson i<<1
#define rson (i<<1) + 1
#include
using namespace std;
vectorve[maxn];
LL add[maxn * 4], l[maxn], r[maxn], index, ha[maxn], deep[maxn];
LL va[maxn];
void dfs(int pre, int fa)
{
     l[pre] = ++index;
     deep[pre] = deep[fa] + 1;
     for(int i = 0; i < ve[pre].size(); i++) if(ve[pre][i] != fa) dfs(ve[pre][i], pre);
     r[pre] = index;
}
void pushDown(int i)
{
    add[lson] += add[i];
    add[rson] += add[i];
    add[i] = 0;
}
void update(int i, int l, int r, int L, int R, int ADD)
{
     if(l == L && r == R)
     {
         add[i] += ADD;
         return ;
     }
     pushDown(i);
     int mid = (l + r) / 2;
     if(R <= mid)  update(lson, l, mid, L, R, ADD);
     else if(L > mid) update(rson, mid + 1, r, L, R, ADD);
     else {
          update(lson, l, mid, L, mid, ADD);
          update(rson, mid + 1, r, mid + 1, R, ADD);
     }
}
LL query(int i, int l, int r, int index)
{
   if(l == r) return add[i];
   pushDown(i);
   int mid = (l + r) / 2;
   if(index <= mid) return query(lson, l, mid, index);
   else return query(rson, mid + 1, r, index);
}
int main()
{
    LL n, m;
    scanf("%I64d %I64d", &n, &m);
    for(int i = 1; i <= n; i++) scanf("%I64d", &va[i]);
    for(int i = 1; i < n; i++)
    {
        LL a, b;
        scanf("%I64d %I64d", &a, &b);
        ve[a].push_back(b);
        ve[b].push_back(a);
    }
    dfs(1, 0);
    //for(int i = 1; i <= n; i++) printf("%d %d")
    while(m--)
    {
         int a, b, c;
         scanf("%d", &a);
         if(a == 1)
         {
            scanf("%d%d", &b, &c);
            if(deep[b] % 2 == 0) c = -c;
            //printf("%I64d ** %I64d\n", l[b], r[b]);
            update(1, 1, index, l[b], r[b], c);
         }
         else
         {
             scanf("%d", &b);
             LL ADD = query(1, 1, index, l[b]);
             if(deep[b] % 2 == 0) ADD = -ADD;
             printf("%I64d\n", va[b] + ADD);
         }
    }
    //system("pause");
    return 0;
}

你可能感兴趣的:(线段树)