Skip to content

Commit

Permalink
Update BIT - Binary Indexed Tree (Fenwick Tree).cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
Ashishgup1 authored Jul 15, 2020
1 parent 4dfd302 commit 16c54ef
Showing 1 changed file with 27 additions and 69 deletions.
96 changes: 27 additions & 69 deletions BIT - Binary Indexed Tree (Fenwick Tree).cpp
Original file line number Diff line number Diff line change
@@ -1,34 +1,3 @@
1D BIT:

int bit[N];

void update(int idx, int val)
{
while(idx<=n)
{
bit[idx]+=val;
idx+=idx&-idx;
}
}

int pref(int idx)
{
int ans=0;
while(idx>0)
{
ans+=bit[idx];
idx-=idx&-idx;
}
return ans;
}

int rsum(int l, int r)
{
return pref(r) - pref(l-1);
}

----------------------------------------------------------------------------------------------------------------------

struct BIT
{
int N;
Expand All @@ -49,15 +18,6 @@ struct BIT
}
}

void updateMax(int idx, int val)
{
while(idx <= N)
{
bit[idx] = max(bit[idx], val);
idx += idx & -idx;
}
}

int pref(int idx)
{
int ans = 0;
Expand All @@ -74,6 +34,31 @@ struct BIT
return pref(r) - pref(l - 1);
}

//returns first index such that pref[idx] >= val

int search(int val)
{
int curSum = 0, pos = 0;
for(int i = log2(N) + 1; i >= 0; i--)
{
if(pos + (1 << i) < N && curSum + bit[pos + (1 << i)] < val)
{
curSum += bit[pos + (1 << i)];
pos += (1 << i);
}
}
return pos + 1;
}

void updateMax(int idx, int val)
{
while(idx <= N)
{
bit[idx] = max(bit[idx], val);
idx += idx & -idx;
}
}

int prefMax(int idx)
{
int ans = -2e9;
Expand All @@ -86,37 +71,10 @@ struct BIT
}
};

Multiple BIT:

int bit[2][N];

void update(int i, int idx, int k)
{
while(idx<=n)
{
bit[i][idx]+=k;
idx+=idx&-idx;
}
}

int pref(int i, int idx)
{
int ans=0;
while(idx>0)
{
ans+=bit[i][idx];
idx-=idx&-idx;
}
return ans;
}

int rsum(int i, int l, int r)
{
return pref(i, r) - pref(i, l-1);
}

//Problem 1: https://codeforces.com/contest/1073/problem/D
//Solution 1: https://codeforces.com/contest/1073/submission/44863255

//Problem 2: https://www.hackerrank.com/contests/university-codesprint-4/challenges/unique-art/problem
//Solution 2: http://p.ip.fi/T9YM

//Problem 3: https://csacademy.com/contest/round-47/task/cut-the-trees/statement/

0 comments on commit 16c54ef

Please sign in to comment.