Cod sursa(job #2942590)

Utilizator DenisONIcBanu Denis Andrei DenisONIc Data 19 noiembrie 2022 21:40:58
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.56 kb
#include <bits/stdc++.h>
using namespace std;
void debug_out() { cerr << endl; }
template<class T> ostream& prnt(ostream& out, T v) { out << v.size() << '\n'; for(auto e : v) out << e << ' '; return out;}
template<class T> ostream& operator<<(ostream& out, vector <T> v) { return prnt(out, v); }
template<class T> ostream& operator<<(ostream& out, set <T> v) { return prnt(out, v); }
template<class T1, class T2> ostream& operator<<(ostream& out, map <T1, T2> v) { return prnt(out, v); }
template<class T1, class T2> ostream& operator<<(ostream& out, pair<T1, T2> p) { return out << '(' << p.first << ' ' << p.second << ')'; }
template <typename Head, typename... Tail> void debug_out(Head H, Tail... T) { cerr << " " << H; debug_out(T...);}
#define dbg(...) cerr << #__VA_ARGS__ << " ->", debug_out(__VA_ARGS__)
#define dbg_v(x, n) do{cerr<<#x"[]: ";for(int _=0;_<n;++_)cerr<<x[_]<<" ";cerr<<'\n';}while(0)
#define dbg_ok cerr<<"OK!\n"
#define ll long long
#define ld long double
#define ull unsigned long long
#define pii pair<int,int>
#define MOD 1000000007
#define zeros(x) x&(x-1)^x
#define fi first
#define se second
#define NMAX 500005
const long double PI = acos(-1);


template<class T = int>
struct AIB {
	int n;
  T* aib;

  AIB(int _n) {
  	aib = new T[_n+1];
  	n = _n + 1;
  }

  void update(int p, T val) {
    for(; p < n; p += p & (-p)) aib[p] += val;
  }

  T query(int p) {
    T res;
    for(res = 0; p; p &= p - 1) res += aib[p];
    return res;
  }

	// get sum on interval [l,r]
  T query(int l, int r) {
    return query(r) - query(l - 1);
  }

  // search first position k s.t. sum[1,k] = val, return -1 else
  T search(T val) {
  	int step;
  	for (step = 1; step < n; step <<= 1);

  	for (int i = 0; step; step >>= 1) {
  		if(i + step <= n) {
  			if (val >= aib[i+step]) {
  				i += step, val -= aib[i];
  				if (!val) return i;
  			}
  		}
  	} 

  	return -1;
  }

  void reset() {
  	memset(aib, 0, sizeof(T) * n);
  }
};
// AIB<int> aib(n) <--- before c++17 you need to specify the type


int n, m;

int main(){
  ios::sync_with_stdio(false);
 	freopen("aib.in","r",stdin);
 	freopen("aib.out","w",stdout); 


 	scanf("%d%d", &n, &m);
 	AIB<int> aib(n);

 	for (int i=1;i<=n;i++) {
 		int x;
 		scanf("%d", &x);
 		aib.update(i, x);
 	}

 	for (int i=1;i<=m;i++) {
 		int t, a, b;
 		scanf("%d", &t);
 		switch (t){
 			case 0:
 				scanf("%d%d", &a, &b);
 				aib.update(a, b);
 				break;
 			case 1:
 				scanf("%d%d", &a, &b);
 				cout << aib.query(a, b) << '\n';
 				break;
 			case 2:
 				scanf("%d", &a);
 				cout << aib.search(a) << '\n';
 				break;
 		}
 	}


  return 0;
}