icpc_library

This documentation is automatically generated by online-judge-tools/verification-helper

View the Project on GitHub ebi-fly13/icpc_library

:heavy_check_mark: fenwick tree
(data_structure/fenwick_tree.hpp)

説明

配列 $a$ に対して、$1$ 点加算、区間和が $O(\log N)$ でできるデータ構造。

add(int p, T x)

a[p] に $x$ を加算

prefix_sum(int p)

sum(a[0], …, a[p-1]) を返す。

sum(int l, int r)

sum(a[l], …, a[r-1]) を返す。

Depends on

Verified with

Code

#pragma once

#include "../template/template.hpp"

namespace lib {

template <class T> struct fenwick_tree {
  private:
    int n;
    std::vector<T> data;

  public:
    fenwick_tree(int n) : n(n), data(n + 1) {}

    void add(int p, T x) {
        assert(0 <= p && p < n);
        p++;
        for (int i = p; i <= n; i += i & -i) {
            data[i] += x;
        }
    }

    T prefix_sum(int p) const {
        assert(0 <= p && p <= n);
        T ret = 0;
        for (int i = p; i > 0; i -= i & -i) {
            ret += data[i];
        }
        return ret;
    }

    T sum(int l, int r) const {
        return prefix_sum(r) - prefix_sum(l);
    }
};

}  // namespace lib
#line 2 "data_structure/fenwick_tree.hpp"

#line 2 "template/template.hpp"

#include <bits/stdc++.h>

#define rep(i, s, n) for (int i = (int)(s); i < (int)(n); i++)
#define rrep(i, s, n) for (int i = (int)(n)-1; i >= (int)(s); i--)
#define all(v) v.begin(), v.end()

using ll = long long;
using ld = long double;
using ull = unsigned long long;

template <typename T> bool chmin(T &a, const T &b) {
    if (a <= b) return false;
    a = b;
    return true;
}
template <typename T> bool chmax(T &a, const T &b) {
    if (a >= b) return false;
    a = b;
    return true;
}

namespace lib {

using namespace std;

}  // namespace lib

// using namespace lib;
#line 4 "data_structure/fenwick_tree.hpp"

namespace lib {

template <class T> struct fenwick_tree {
  private:
    int n;
    std::vector<T> data;

  public:
    fenwick_tree(int n) : n(n), data(n + 1) {}

    void add(int p, T x) {
        assert(0 <= p && p < n);
        p++;
        for (int i = p; i <= n; i += i & -i) {
            data[i] += x;
        }
    }

    T prefix_sum(int p) const {
        assert(0 <= p && p <= n);
        T ret = 0;
        for (int i = p; i > 0; i -= i & -i) {
            ret += data[i];
        }
        return ret;
    }

    T sum(int l, int r) const {
        return prefix_sum(r) - prefix_sum(l);
    }
};

}  // namespace lib
Back to top page