Cod sursa(job #2683526)

Utilizator cyg_TheoPruteanu Theodor cyg_Theo Data 11 decembrie 2020 16:19:48
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.52 kb
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <vector>
#include <queue>
#include <stack>

using namespace std;

const int NMAX = 100000 + 5; //10^5

const int INF = 1e9;
const double eps = 1e-9;

#define fileI freopen(".in","r",stdin);
#define fileO freopen(".out","w",stdout);
#define IO(name) \
	freopen(name".in","r",stdin); \
	freopen(name".out","w",stdout);

int v[NMAX];
int aib[NMAX];

void update(int index, int value){
	v[index] += value;

	for(; index < NMAX; index += index&-index)
		aib[index] += value;

}

//sum from of [1,index]
int query(int index){

	int answer = 0;
	
	for(; index; index -= index&-index)
		answer += aib[index];

	return answer;
}

void solve();

int main(){
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);

	int t;

	t = 1;
	//scanf("%d",&t);

	for(;t;t--){
		solve();
	}

	return 0;
}

void solve(){
	IO("aib");

	int n,m;
	scanf("%d%d",&n,&m);
	for(int i=1;i<=n;++i){
		scanf("%d",&v[i]);
		update(i,v[i]);
	}

	int q,a,b;
	for(int i=1;i<=m;++i){
		scanf("%d",&q);

		//v[a]+=b
		if(q==0){
			scanf("%d%d",&a,&b);
			update(a,b);
		}
		//query for sum of [a,b] interval
		if(q==1){
			scanf("%d%d",&a,&b);
			printf("%d\n",query(b)-query(a-1));
		}
		if(q==2){
			scanf("%d",&a);
			int nowSum=0,best=0;

			for(int step=17; step>=0; step--){
				if(best+(1<<step)<NMAX && nowSum + aib[best+(1<<step)]<a){
					best+=(1<<step);
					nowSum+=aib[best];
				}
			}
			best++;
			if(query(best)==a)
				printf("%d\n",best);
			else
				printf("-1\n");
		}
	}
}