Cod sursa(job #2602185)

Utilizator andreisontea01Andrei Sontea andreisontea01 Data 16 aprilie 2020 09:51:46
Problema Arbori indexati binar Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.06 kb
#include <bits/stdc++.h>

using namespace std;

const int MAXN = 100005;

int v[MAXN], aib[MAXN];

int n;

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

void update(int pos, int val){
    while(pos <= n){
        aib[pos] += val;
        pos += lsb(pos);
    }
}

int query(int x){
    int ans = 0;
    while(x){
        ans += aib[x];
        x -= lsb(x);
    }
    return ans;
}

int main()
{
    ifstream fin("aib.in");
    ofstream fout("aib.out");
    ios::sync_with_stdio(false);
    fin.tie(0);
    fout.tie(0);
    int m;
    fin >> n >> m;
    for(int i = 1; i <= n; ++i){
        fin >> v[i];
        update(i, v[i]);
    }
    while(m--){
        int c, a, b;
        fin >> c >> a;
        if(c < 2) fin >> b;
        if(c == 0) update(a, b);
        else if(c == 1) fout << query(b) - query(a - 1) << "\n";
        else{
            int pos = 1;
            while(pos <= n && query(pos) < a) pos += lsb(pos);
            if(aib[pos] == a) fout << pos << "\n";
            else fout << "-1\n";
        }
    }
    return 0;
}