Skip to content

Instantly share code, notes, and snippets.

@keon
Created February 17, 2017 17:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save keon/5dc814a0d9b5cbbd35c4804322f2ba28 to your computer and use it in GitHub Desktop.
Save keon/5dc814a0d9b5cbbd35c4804322f2ba28 to your computer and use it in GitHub Desktop.
class Fenwick{
private:
const int maxN = 10000;
public:
int table[maxN];
int sumQuery(int a, int b){
return sumQuery(b) - sumQuery(a-1);
}
int sumQuery(int k){
int ret = 0;
while (k > 0) {
ret += table[k];
k &= k - 1;
}
return ret;
}
void adjust(int i, int adj){
while(i < maxN){
table[i] += adj;
i += (i & (-i));
}
}
int getValue(int i) {
return sumQuery(i, i);
}
int findFirst(int k) {
int L = 1, R = maxN - 1;
while (R - L > 1) {
int M = (R+L) / 2;
int val = sumQuery(M);
if (val < k)
L = M + 1;
else
R = M;
}
int LVal = sumQuery(L);
if (LVal >= k)
return L;
return R == L || sumQuery(R) < k ? -1 : R;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment