1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
| #include <bits/stdc++.h> #if (1) #ifdef _MSC_VER #include <intrin.h> #endif int countl_zero(unsigned int n) { #ifdef _MSC_VER unsigned long index; _BitScanReverse(&index, n); return 31 - index; #else return __builtin_clz(n); #endif } #else int countl_zero(unsigned int n) { int res = 0; while (!(x & 0x80000000)) ++res, x <<= 1; return res; } #endif template <class T, T (*e)(), T (*sum)(T, T), T (*diff)(T, T) = nullptr> class fenwick_tree { protected: int n_; std::vector<T> data_;
public: fenwick_tree() : fenwick_tree(0) {} explicit fenwick_tree(int n) : n_(n), data_(n, e()) {} explicit fenwick_tree(const std::vector<T>& a) : n_(int(a.size())), data_(a.size(), e()) { for (int p = 1; p <= n_; ++p) { data_[p - 1] = sum(data_[p - 1], a[p - 1]); if (int q = p + (p & -p); q <= n_) data_[q - 1] = sum(data_[q - 1], data_[p - 1]); } } fenwick_tree(fenwick_tree const&) = default; fenwick_tree(fenwick_tree&&) = default; fenwick_tree& operator=(fenwick_tree const&) = default; fenwick_tree& operator=(fenwick_tree&&) = default;
void add(int p, T x) { assert(0 <= p && p < n_); ++p; while (p <= n_) { data_[p - 1] = sum(data_[p - 1], x); p += p & -p; } } T prefix_sum(int p) const { assert(-1 <= p && p < n_); ++p; T s = e(); while (p > 0) { s = sum(s, data_[p - 1]); p -= p & -p; } return s; } T sum_range(int l, int r) const { assert(0 <= l && l <= r && r <= n_); static_assert(diff != nullptr); return diff(prefix_sum(r - 1), prefix_sum(l - 1)); } int kth(T k) const { T s = 0; int x = 0; for (int i = 31 - countl_zero(n_); i >= 0; --i) { x += 1 << i; if (x >= n_ || sum(s, data_[x - 1]) >= k) x -= 1 << i; else s = sum(s, data_[x - 1]); } return x; } int size() const { return n_; } }; template <class T> struct _fenwick_sum { static T e() { return 0; } static T sum(T a, T b) { return a + b; } static T diff(T a, T b) { return a - b; } using type = fenwick_tree<T, e, sum, diff>; }; template <class T> using fenwick_sum = typename _fenwick_sum<T>::type;
|