(娱乐向)learn how to use Segment Tree

· · 个人记录

众所周知,线段树的理论平衡是 e 叉。

↓树状数组 1。

#include <bits/stdc++.h>
using namespace std;
using numbers::e;
constexpr int N = 5e5 + 9;
constexpr double ie = 1. / e;
int n, m, sgt[N << 1];
inline void update(int x, int d) {
  for (x += n; x; x *= ie) sgt[x] += d;
}
inline int query(int l, int r) {
  int ans = 0;
  for (l += n, r += n; int(l * ie) != int(r * ie); l *= ie, r *= ie) {
    while (int(l * ie) == int((l - 1) * ie)) ans += sgt[l++];
    while (int(r * ie) == int((r - 1) * ie)) ans += sgt[--r];
  }
  return accumulate(sgt + l, sgt + r, ans);
}
signed main() {
  cin.tie(nullptr)->sync_with_stdio(false);
  cin >> n >> m;
  for (int i = 0; i < n; ++i) cin >> sgt[i + n];
  for (int i = (n << 1) - 1; i >= e; --i) sgt[int(i * ie)] += sgt[i];
  for (int op; m; --m)
    if (cin >> op; op == 1) {
      int x, d;
      cin >> x >> d;
      update(--x, d);
    } else {
      int l, r;
      cin >> l >> r;
      cout << query(l - 1, r) << '\n';
    }
  return cout << flush, 0;
}

怎么还有信任速度的,都浮点数乘法了这玩意就图一乐呵。

极少部分情况下同平衡下三叉树比二叉树快,e 叉树理论上可以谋得一席,但说真的,没必要。