Cod sursa(job #3236834)

Utilizator luc3lexaAlexandrescu Luca luc3lexa Data 2 iulie 2024 18:31:15
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.19 kb
#include <iostream>
#include <fstream>
#include <bits/stdc++.h>
using namespace std;
ifstream fin("aib.in");
ofstream fout("aib.out");

const int nmax = 1e5+10;
vector<int> values(nmax,0),aib(nmax,0);
int n,m,operatie;

int lsb(int number){
	return (number & (-number));
}

int sum(int index){
	int ans = 0;
	for( ;index ;index -= lsb(index)){
		ans += aib[index];
	};
	return ans;
}

void update(int index,int valoare){
	for( ;index <=n; index += lsb(index)){
		aib[index] += valoare;
	}
};

void read_input(){
	fin >> n >> m;
	int aux;
	for(int i = 1; i <=n; i++){
		fin >> aux;
		update(i,aux);
	}
}
int bin_search(int value){
	int st = 1,dr = n,ans = n+1;
	while(st <= dr){
		int mij =  (st+dr)/2;
		if(value <= sum(mij)){
		    ans = mij;
			dr = mij-1;
		}else{
			st = mij+1;
		}
	};
	if(sum(ans) == value){
		return ans;
	}else{
		return -1;
	}
}
int main(){
    read_input();
	for(int i = 1; i <=m; i++){
		fin >> operatie;
		if(operatie == 0){
			int poz,val;
			fin >> poz >> val;
			update(poz,val);
		}else if(operatie == 1){
			int poz_1,poz_2;
			fin >> poz_1 >> poz_2;
			fout << sum(poz_2)-sum(poz_1-1) << '\n';
		}else{
			int val;fin >> val;
			fout << bin_search(val) << '\n';
		}
	};
	return 0;
}