template <typename T> structFenwick { int n; std::vector<T> a; Fenwick(int size) : n(size), a(n) {} Fenwick(std::vector<T> &v) : n(v.size()), a(n) { for (int i = 0; i < n; i++) { add(i, v[i]); } } voidadd(int x, T v){ for (int i = x + 1; i <= n; i += i & -i) { a[i - 1] += v; } } /// @brief sum of [0, r] T sum(int r){ T ans = T{}; if (r < 0) { return ans; } for (int i = r + 1; i > 0; i -= i & -i) { ans += a[i - 1]; } return ans; } /// @brief sum of [l, r] T sum(int l, int r){ returnsum(r) - sum(l - 1); } intkth(T k){ int x = 0; for (int i = 1 << std::__lg(n); i; i /= 2) { if (x + i <= n && k >= a[x + i - 1]) { x += i; k -= a[x - 1]; } } return x; } };
constexprint inf = 1e9; /// @note when use this, disable `sum(l, r)` and `kth(k)` ! structMax { i64 v; Max(i64 val = -inf) : v(val) {} Max &operator+=(const Max &rhs) { v = std::max(v, rhs.v); return *this; } };