Cod sursa(job #3365527)

Utilizator TimofeiFilipTimofei Filip Emanuel TimofeiFilip Data 22 septembrie 2026 10:03:50
Problema Arbori indexati binar Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.95 kb
#include<bits/stdc++.h>
using namespace std;

const int NMAX = 1e5 + 10;
typedef long long int ll;

ll tree[NMAX], v[NMAX];
int n, queries;

void compute_input() {
    scanf("%d %d", &n, &queries);
    for (int i = 1; i <= n; i++) scanf("%lld", &v[i]);
}

void add(int index, ll value) {
    while (index <= n) {
        tree[index] += value;
        index = index + (index & -index);
    }
}
void build_tree() {
    for (int i = 1; i <= n; i++)
        add(i, v[i]);
}
ll get_prefix(int index) {
    if (index <= 0) return 0;
    ll sum = 0;
    while (index >= 1) {
        sum += tree[index];
        index = index - (index & -index);
    }
    return sum;
}

ll query(int left, int right) {
    return get_prefix(right) - get_prefix(left - 1);
}
void update(int position, int new_value) {
    add(position, new_value);
}
int order_sum(ll target) {
    int step = 1;
    while (step << 1 <= n) {
        step = step << 1;
    }
    int position = 0;
    ll current_sum = 0;
    for (; step > 0; step >>= 1) {
        int next_position = position + step;
        if (next_position > n) continue;
        if (current_sum + tree[next_position] >= target ) continue;
        position = next_position;
        current_sum += tree[next_position];
    }
    position++;
    return (position <= n && current_sum + tree[position] == target) ? position : -1;
}
void compute_output() {
    for (; queries > 0; queries--) {
        int op, x, y;
        scanf("%d %d", &op, &x);
        if (op == 1) {
            scanf("%d", &y);
            printf("%lld\n", query(x, y));
        }
        else if (op == 0) {
            scanf("%d", &y);
            update(x, y);
        }
        else {
            printf("%d\n", order_sum(x));
        }
    }
}

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

    compute_input();
    build_tree();
    // for(int i  = 1; i <= n; i++)
    //     printf("%lld ", tree[i]);
    printf("\n");
    compute_output();
    return 0;
}