Cod sursa(job #3357801)

Utilizator TestLicenta123Test Test TestLicenta123 Data 13 iunie 2026 15:04:00
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

class AIB {
private:
    vector<long long> aib;
    int n;

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

public:
    AIB(int size) {
        n = size;
        aib.assign(n + 1, 0);
    }

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

    long long query(int pos) {
        long long sum = 0;
        while (pos > 0) {
            sum += aib[pos];
            pos -= lsb(pos);
        }
        return sum;
    }

    int find(long long sum) {
        int pos = 0;
        long long current = 0;
        int step;
        for (step = 1; step <= n; step <<= 1);
        for (step >>= 1; step > 0; step >>= 1) {
            if (pos + step <= n && current + aib[pos + step] < sum) {
                current += aib[pos + step];
                pos += step;
            }
        }
        return pos + 1;
    }
};

int main() {
    ifstream input("aib.in");
    ofstream output("aib.out");
    int n, m;
    input >> n >> m;

    AIB tree(n);
    vector<int> v(n + 1);

    for (int i = 1; i <= n; ++i) {
        input >> v[i];
        tree.update(i, v[i]);
    }

    while (m--) {
        int q;
        input >> q;
        if (q == 0) {
            int a, b;
            input >> a >> b;
            tree.update(a, b);
        } else if (q == 1) {
            int a, b;
            input >> a >> b;
            long long result = tree.query(b) - tree.query(a - 1);
            output << result << '\n';
        } else if (q == 2) {
            int a;
            input >> a;
            long long total = tree.query(n);
            if (a > total) {
                output << -1 << '\n';
            } else {
                int pos = tree.find(a);
                if (tree.query(pos) == a) {
                    output << pos << '\n';
                } else {
                    output << -1 << '\n';
                }
            }
        }
    }

    return 0;
}