Cod sursa(job #2019131)

Utilizator workwork work work Data 7 septembrie 2017 09:32:57
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.95 kb
#include <bits/stdc++.h>

using namespace std;

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

int n, aib[100005], a, b, x, q;

void upd(int pos, int x)
{
    while(pos <= n)
    {
        aib[pos] += x;
        pos += pos & (-pos);
    }
}

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

int Find(int a)
{
    int l = 1, r = n, mid, aux;
    while(l <= r)
    {
        mid = (l+r) >> 1;
        aux = query(mid);
        if(aux == a) return mid;
        if(aux < a) l = mid+1;
        else r = mid-1;
    }
    return -1;
}

int main()
{
    F >> n >> q;
    for(int i = 1; i <= n; ++ i) F >> x, upd(i, x);
    while(q--)
    {
        F >> x;
        if(!x) F >> a >> b, upd(a, b);
        else if(x == 1) F >> a >> b, G << query(b) - query(a-1) << '\n';
        else F >> a, G << Find(a) << '\n';
    }
    return 0;
}