Cod sursa(job #2589602)

Utilizator tomitza.1604Sacuiu TomaAndrei tomitza.1604 Data 26 martie 2020 16:43:44
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.24 kb
#include <iostream>
#include <fstream>

using namespace std;


const int N = 100001;
const int L = 16;
int n, m, z, t, aib[N];

ifstream in("aib.in");
ofstream out("aib.out");


int caut(int x){
    if(x == 0){
        return -1;
    }
    int p = 0, pas = 1 << L;
    while( pas != 0){
        if(p + pas <= n && aib[p+pas] <= x){
            p += pas;
            x -= aib[p];
        }
        pas /= 2;
    }
    if( x != 0){
        return -1;
    }
    return p;
}


void actualizare(int p, int val){
    while (p <= n){
        aib[p] += val;
        p += (p & (-p));
    }
}

int interog(int p){
    int s = 0;
    while(p){
        s += aib[p];
        p -= (p & (-p));
    }
    return s;
}

int main()
{
    in >> n >> m;
    for(int i = 1; i <= n; i++){
        in >> z;
        actualizare(i, z);
    }
    for(int i = 1; i <= m; i++){
        int x, y;
        in >> t;
        if(t == 0){
            in >> x >> y;
            actualizare(x, y);
        }
        if( t == 1){
            in >> x >> y;
            out << interog(y) - interog(x-1) << '\n';
        }
        if( t == 2){
            in >> x;
            out << caut(x) << '\n';
        }
    }

    return 0;
}