版本比较
数据结构模版
正文
增加 23 行删除 94 行
12345678910111213141516171819202122232425262728293031323334353637383940414243441246348495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596456789101112131415161718192021222324252627# 1.树状数组```cpptemplate<class T> struct BIT { T *c; int n; int lowbit (int x) { return x & -x; } void update (int x, T val) { while (x <= n) { c[x] += val; x += lowbit(x); } } T query (int x) { T res = 0; while (x > 0) { res += c[x]; x -= lowbit(x); } return res; } T query (int l, int r) { return query(r) - query(l - 1); } void build (int n_, int a[]) { n = n_; c = new T[n_ + 1](); for (int i = 1; i <= n; i++) update(i, a[i]); } void build (int n_) { n = n_; c = new T[n_ + 1](); } void clear() { if (c) delete[] c; n = 0; } ~BIT() { if (c) delete[] c; }};```# Fenwick_Tree
# 2.线段树(单点修改,区间查询sum)```cpptemplate<class T> struct RMQ_sum { T *t; int n; void build(int id, int l, int r, int a[]) { if (l == r) { t[id] = a[l]; return; } int mid = l + (r - l) / 2; build(id * 2, l, mid, a); build(id * 2 + 1, mid + 1, r, a); t[id] = t[id * 2] + t[id * 2 + 1]; } void build(int n_, int a[]) { n = n_; t = new T[(n + 1) * 4](); build(1, 1, n, a); } void build(int n_) { n = n_; t = new T[(n + 1) * 4](); } void update(int id, int l, int r, int idx, T value) { if (l == r) { t[id] += value; return; } int mid = l + (r - l) / 2; if (idx <= mid) update(id * 2, l, mid, idx, value); else update(id * 2 + 1, mid + 1, r, idx, value); t[id] = t[id * 2] + t[id * 2 + 1]; } void update(int idx, int value) { update(1, 1, n, idx, value); } T query(int id, int l, int r, int ql, int qr) { if (r < ql || l > qr) return 0; if (ql <= l && r <= qr) return t[id]; int mid = l + (r - l) / 2; return query(id * 2, l, mid, ql, qr) + query(id * 2 + 1, mid + 1, r, ql, qr); } T query(int l, int r) { return query(1, 1, n, l, r); } ~RMQ_sum() { if (t) delete[] t; }
template<class T = long long> class Fenwick {public: Fenwick(int n_) : n(n_), bit(n + 1, T{}) {} void modify(int x, T v) { assert(x > 0); for (; x <= n; x += lowbit(x)) bit[x] += v; } T query(int x) { assert(x > 0); T res = 0; for (; x; x -= lowbit(x)) res += bit[x]; return res; } T query(int l, int r) { if (l > r) return 0; if (l == 1) return query(r); else return query(r) - query(l - 1); }private: int n; vector<T> bit; int lowbit(int x) { return x & -x; }};```