Cod sursa(job #2763086)

Utilizator Bulboaca_EugenBulboaca Alexandru Eugen Bulboaca_Eugen Data 11 iulie 2021 15:44:11
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.15 kb
#include <bits/stdc++.h>
#define zeros(x) x & (-x)
using namespace std;

const int MAXN = 1e5 + 65;
const int INF = 1e8;

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

int aib[MAXN], n, cnt = 1;

void update(int poz, int val){

    for(int i = poz; i <= n; i += zeros(i))
        aib[i] += val;
}

int query(int poz){
    int sum = 0;
    for(int i = poz; i > 0 ; i -= zeros(i))
        sum += aib[i];
    return sum;
}

int binsearch(int a){
    int current = 0;
    for(int i = 30; i >= 0; --i){
        if((current + (1 << i)) <= n and query((current + (1 << i))) < a)
            current += (1 << i);
    }
    if(query(current + 1) == a) return current + 1;
    return -1;
}

int main(){

    int m; fin >> n >> m;
    for(int i = 1; i <= n; ++i){
        int x; fin >> x;
        update(i, x);
    }
    cnt = 0;
    for(int i = 1; i <= m; ++i){
        int type, x, y; fin >> type >> x;
        if(type == 2) fout << binsearch(x) << '\n';
        else if(type == 1){
            fin >> y;
            fout << query(y) - query(x - 1) << '\n';
        }
        else fin >> y, update(x, y);
    }
    return 0;
}