Cod sursa(job #2982789)

Utilizator tiberia_farkasFarkas Tiberia tiberia_farkas Data 20 februarie 2023 21:11:35
Problema Arbori indexati binar Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.16 kb
#include <bits/stdc++.h>

using namespace std;

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

int a[100001], n;

int query(int pi) {
    int sum = 0;
    for ( int i = pi; i > 0; i -= (i&-i) ) {
        sum += a[i];
    }
    return sum;
}

void update(int p, int x) {
    for ( int i = p; i <= n; i += (i&-i) ) {
        a[i] += x;
    }
}

int Search(int x) {
    int st, dr, mij, i;
    st = 1;
    dr = n;
    while ( st <= dr ) {
        mij = ( st + dr ) / 2;
        i = query(mij);
        if ( i > x ) dr = mij - 1;
        else if ( i < x ) st = mij + 1;
        else return i;
    }
    return -1;
}

int main() {
    int m, c, i, x, y;
    fin >> n >> m;
    for ( i = 1; i <= n; ++i ) {
        fin >> x;
        update(i, x);
    }
    //for ( i = 1; i <= n; ++i ) cout << a[i] << " ";
    //cout << '\n';
    for ( i = 1; i <= m; ++i ) {
        fin >> c;
        if ( c == 2 ) {
            fin >> x;
            fout << Search(x) << '\n';
        } else {
            fin >> x >> y;
            if ( c == 0 ) update(x, y);
            else fout << query(y) - query(x-1) << '\n';
        }
    }
    return 0;
}