Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Binary indexed trees #593

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions binary_indexed_trees/bit.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
#include<iostream>
#include<string>
#include<vector>
#include<sstream>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<numeric>
#include<map>
#include<set>
#include<queue>
using namespace std ;
int tree[200002];
int MaxVal=200002;

int read(int idx){
if(idx==0)return 0;
int sum = 0;
while (idx > 0){
sum += tree[idx];
idx -= (idx & -idx);
}
return sum;
}

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

int main(){

memset(tree,0,sizeof(tree));
update(3,1);
update(4,1);
cout<<read(5)<<endl;
update(10,2);
update(8,3);
cout<<read(9)<<endl;

return 0;
}

85 changes: 85 additions & 0 deletions binary_indexed_trees/orders_spoj.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
#include<iostream>
#include<string>
#include<vector>
#include<sstream>
#include<cmath>
#include<algorithm>
#include<numeric>
#include<map>
#include<set>
#include<queue>
using namespace std ;
int tree[200002];
int MaxVal=200001;

int read(int idx){
if(idx==0)return 0;
int sum = 0;
while (idx > 0){
sum += tree[idx];
idx -= (idx & -idx);
}
return sum;
}


int get(int sum){
int idx=1<<17;
int ac=0;

while(idx!=0){
if(ac+idx>MaxVal || tree[ac+idx]>= sum){
idx>>=1;
}else{
sum-=tree[ac+idx];
ac+=idx;
idx>>=1;
}
}

return ac+1;
}


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

int main(){

int tc;
scanf("%d",&tc);

while(tc--){
memset(tree,0,sizeof(tree));
int n;
scanf("%d",&n);
int c[n];

for(int i=0;i<n;i++)
scanf("%d",&c[i]);

for(int i=0;i<n;i++)
update(i+1,1);

int val=n;
int dev[n];
for(int i=n-1;i>=0;i--){
dev[i]=get(val-c[i]);
update(dev[i],-1);
val--;
}

for(int i=0;i<n;i++){
if(i!=n-1)printf("%d ",dev[i]);
else printf("%d",dev[i]);
}

printf("\n");
}

return 0;
}