Created
December 16, 2018 21:20
-
-
Save Guiorgy/11def228618ab6afe9c2c2765acbc993 to your computer and use it in GitHub Desktop.
FenwickTree structure for c++
This file contains 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
struct FenvickTree { | |
struct Node { | |
int Value; | |
int Sum; | |
int Parent; | |
int Next; | |
}; | |
vector<Node> Tree; | |
int Sum(int index) { | |
if (index < 0) return 0; | |
int sum = 0; | |
do { | |
sum += Tree[index].Sum; | |
index = Tree[index].Parent; | |
} while (index != -1); | |
return sum; | |
} | |
int Sum(int left, int right) { | |
return Sum(right) - Sum(left - 1); | |
} | |
int Calc(int left, int right) { | |
int sum = 0; | |
for (int i = left; i < right; ++i) { | |
sum += Tree[i].Value; | |
} | |
return sum; | |
} | |
void Initialize(vector<int> * values) { | |
int size = (*values).size(); | |
Node zero; | |
zero.Next = -1; | |
zero.Parent = -1; | |
zero.Sum = 0; | |
zero.Value = 0; | |
Tree.resize(size, zero); | |
for (int i = 0; i < size; ++i) { | |
Tree[i].Value = (*values)[i]; | |
int p = (i & (i + 1)) - 1; | |
if (p < 0) Tree[i].Parent = -1; | |
else Tree[i].Parent = p; | |
int n = i + 1; | |
n += (n & (-n)) - 1; | |
Tree[i].Next = n; | |
} | |
for (int i = 0; i < size; ++i) { | |
int value = Tree[i].Value; | |
int j = i; | |
do { | |
Tree[j].Sum += value; | |
j = Tree[j].Next; | |
} while (j < size); | |
} | |
} | |
void Push(int value) { | |
Node node; | |
node.Value = value; | |
node.Sum = value; | |
node.Next = -1; | |
int p = (Tree.size() & (Tree.size() + 1)) - 1; | |
if (p < 0) node.Parent = -1; | |
else node.Parent = p; | |
int s = Tree.size() + 1; | |
int n = s + (s & (-s)) - 1; | |
node.Next = n; | |
node.Sum += Calc(s - (s & (-s)), s - 1); | |
Tree.push_back(node); | |
} | |
void Update(int index, int value) { | |
int dif = value - Tree[index].Value; | |
Tree[index].Value = value; | |
do { | |
Tree[index].Sum += dif; | |
index = Tree[index].Next; | |
} while (index < Tree.size()); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment