Created
May 23, 2023 04:56
-
-
Save MikuroXina/fed483ea3a71698e1e15e834241307f2 to your computer and use it in GitHub Desktop.
The implementation of Fenwick tree.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #pragma once | |
| #include <vector> | |
| class Fenwick { | |
| std::vector<size_t> data; | |
| size_t parent(size_t i) const { | |
| return i - (i & (-i)); | |
| } | |
| size_t next(size_t i) const { | |
| return i + (i & (-i)); | |
| } | |
| public: | |
| Fenwick(size_t len) : data(len + 1, 0) {} | |
| size_t sum_to(size_t i) const { | |
| ++i; | |
| size_t sum = 0; | |
| while (0 < i) { | |
| sum += data.at(i); | |
| i = parent(i); | |
| } | |
| return sum; | |
| } | |
| void add(size_t i, size_t val) { | |
| ++i; | |
| while (i < data.size()) { | |
| data[i] += val; | |
| i = next(i); | |
| } | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment