Cod sursa(job #1899756)

Utilizator eu3neuomManghiuc Teodor-Florin eu3neuom Data 2 martie 2017 22:06:25
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.53 kb
#include <bits/stdc++.h>

using namespace std;

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

const int NMax = 1e5 + 5;

int v[NMax];
int Aib[NMax];

inline void Update(int pos, const int &value, const int &n) {
    while(pos <= n) {
        Aib[pos] += value;
        pos += (pos & (-pos));
    }
}

inline int Query(int pos) {
    int sum = 0;
    while(pos > 0) {
        sum += Aib[pos];
        pos -= (pos & (-pos));
    }

    return sum;
}

inline int Solve(const int &value, const int &n) {
    int step = (1 << 30);
    for(int i = 0; step; step >>= 1) {
        if(i + step <= n) {
            if(Query(i + step) == value) {
                return i + step;
            }
            if(Query(i + step) < value) {
                i += step;
            }
        }
    }

    return -1;
}

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

    int n, m;
    fin >> n >> m;

    for(int i = 1; i <= n; i++) {
        int x;
        fin >> x;

        Update(i, x, n);
    }

    for(int i = 1; i <= m; i++) {
        int type;
        fin >> type;

        if(type == 0) {
            int x, y;
            fin >> x >> y;

            Update(x, y, n);
        } else {
            if(type == 1) {
                int x, y;
                fin >> x >> y;

                fout << Query(y) - Query(x - 1) << "\n";
            } else {
                int x;
                fin >> x;

                fout << Solve(x, n) << "\n";
            }
        }
    }

    return 0;
}