【树状数组】【P3372】 【模板】线段树 1

Description

给定一个长度为 (n) 的序列,有 (m) 次操作,要求支持区间加和区间求和。

Limitation

(1 leq n,~m leq 10^5) 序列元素值域始终在 long long 范围内。要求使用树状数组解决

Solution

sb线段树板子题

一直听说这题有树状数组做法,今天刚刚明白。

首先区间加和区间求和可以转化成前缀修改和前缀求和。

考虑一个前缀加操作 update(x, v) 对一次前缀查询 query(y) 的贡献。

(x leq y) 时,贡献为 (x imes v)

当 $ x > y$ 时,贡献为 (y imes v)

考虑分别维护这两种贡献。用第一个序列维护第一种贡献,每次进行 update(x, v) 时在序列 (x) 处加上 (x imes v),代表每个 查询 query(y) ((y geq x)) 都被加上了 (x imes v) 的贡献;用第二个序列维护第二种贡献,在进行 update(x, v) 时在 (x) 处加上 (v),代表每个查询 query(y) ((y < x)) 都会被加上 (y imes v) 的贡献。

对于每个查询 query(y),其答案显然是 (QA(y) + (QB(n) - QB(y)) imes y),其中 (QA) 代表对第一个序列做前缀查询,(QB) 代表对第二个序列做前缀查询。那么直接用树状数组维护这两个贡献即可。

Code

#include <cstdio>

const int maxn = 100005;

int n, m;

struct BIT {
  ll ary[maxn];

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

  void update(int p, const ll &v) {
    if (p == 0) return;
    do ary[p] += v; while ((p += lowbit(p)) <= n);
  }

  ll query(int p) {
    ll _ret = 0;
    do _ret += ary[p]; while (p -= lowbit(p));
    return _ret;
  }
};
BIT leq, geq;

void update(int p, const ll &v);
ll query(int p);

int main() {
  freopen("1.in", "r", stdin);
  qr(n); qr(m);
  for (int i = 1; i <= n; ++i) {
    ll v = 0; qr(v);
    update(i, v); update(i - 1, -v);
  }
  for (ll x, y, z; m; --m) {
    x = 0; qr(x);
    if (x == 1) {
      x = y = z = 0; qr(x); qr(y); qr(z);
      update(y, z);
      update(x - 1, -z);
    } else {
      x = y = 0; qr(x); qr(y);
      qw(query(y) - query(x - 1), '
', true);
    }
  }
  return 0;
}

void update(int i, const ll &v) {
  leq.update(i, i * v);
  geq.update(i, v);
}

ll query(const int p) { return leq.query(p) + (geq.query(n) - geq.query(p)) * p; }
原文地址:https://www.cnblogs.com/yifusuyi/p/11181721.html