Procon

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

View the Project on GitHub K-Yoshizawa/Procon

:heavy_check_mark: Binary Indexed Tree (Fenwick Tree) - 二分索引木
(Library/DataStructure/BinaryIndexedTree.hpp)

Binary Indexed Tree (Fenwick Tree) - 二分索引木

長さ $N$ の数列 $A = (A_1, \dots, A_N)$ に対し、一点加算・区間和取得クエリを効率的に行うことができるデータ構造です。

Function

Constructor

BinaryIndexedTree(int n)

制約

計算量


Add

void Add(int i, T v)

制約

計算量


Sum

(1) T Sum(int i)
(2) T Sum(int l, int r)

制約

計算量


Depends on

Verified with

Code

#include "../Common.hpp"

template<typename T>
struct BinaryIndexedTree{
    public:
    BinaryIndexedTree(int n) : size_(n){
        data_.resize(size_ + 1, 0);
    }

    T Sum(int i){
        T ret = 0;
        for(; i > 0; i -= i & -i) ret += data_[i];
        return ret;
    }
    
    T Sum(int l, int r){
        return Sum(r) - Sum(l - 1);
    }

    void Add(int i, T v){
        for(; i <= size_; i += i & -i) data_[i] += v;
    }

    private:
    int size_;
    vector<T> data_;
};
#line 2 "Library/Common.hpp"

/**
 * @file Common.hpp
 */

#include <algorithm>
#include <array>
#include <bitset>
#include <cassert>
#include <cstdint>
#include <deque>
#include <functional>
#include <iomanip>
#include <iostream>
#include <limits>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
using namespace std;

using ll = int64_t;
using ull = uint64_t;

constexpr const ll INF = (1LL << 62) - (3LL << 30) - 1;
#line 2 "Library/DataStructure/BinaryIndexedTree.hpp"

template<typename T>
struct BinaryIndexedTree{
    public:
    BinaryIndexedTree(int n) : size_(n){
        data_.resize(size_ + 1, 0);
    }

    T Sum(int i){
        T ret = 0;
        for(; i > 0; i -= i & -i) ret += data_[i];
        return ret;
    }
    
    T Sum(int l, int r){
        return Sum(r) - Sum(l - 1);
    }

    void Add(int i, T v){
        for(; i <= size_; i += i & -i) data_[i] += v;
    }

    private:
    int size_;
    vector<T> data_;
};
Back to top page