Cod sursa(job #2231007)

Utilizator CiobaCatalinCioba Catalin CiobaCatalin Data 12 august 2018 17:00:55
Problema Arbori indexati binar Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 1.6 kb
#include <fstream>
#include <vector>
#include <stdio.h>

using namespace std;

typedef long long ll;

ll lsb(ll a) {
    return a & (-a);
}

void update(vector<ll> &vec, int pos, int value) {
    while (pos <= vec.size()) {
        vec[pos - 1] += value;
        pos += lsb(pos);
    }
}

ll query(vector<ll> &vec, ll pos) {
    ll res = 0;

    while (pos != 0) {
        res += vec[pos-1];
        pos -= lsb(pos);
    }

    return res;
}

ll search(vector<ll> &vec, ll value) {
    int start, end;

    start = 0;
    end = vec.size() - 1;

    while (start <= end) {
        int mid = start + (end - start) / 2 + 1;

        ll x = query(vec, mid);
        if (x == value) {
            return mid;
        } else if (x < value) {
            start = mid;
        } else {
            end = mid - 2;
        }
    }

    return -1;
}

int main() {
    ios::sync_with_stdio(false);

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

    int n, m;
    in >> n >> m;

    vector<ll> aib(n, 0);

    int x;
    for (int i = 0; i < n; ++i) {
        in >> x;

        update(aib, i+1, x);
    }

    int type, a, b;
    for (int i = 0; i< m; ++i) {
        in >> type;

        if (type == 0) {
            in >> a >> b;
            update(aib, a, b);
        } else if (type == 1) {
            in >> a >> b;

            ll sum_til_a = 0;
            if (a > 0)
                sum_til_a = query(aib, a-1);
            ll sum_til_b = query(aib, b);

            out << sum_til_b - sum_til_a << endl;
        } else {
            in >> a;
            out << search(aib, a) << endl;
        }
    }

    in.close();
    out.close();
}