Cod sursa(job #2324573)

Utilizator rexlcdTenea Mihai rexlcd Data 21 ianuarie 2019 01:09:07
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.33 kb
#include <bits/stdc++.h>

using namespace std;

int v[100002];
int n, q;

inline void update(int pos, int val)
{
    for(; pos <= n; pos += (pos & -pos))
        v[pos] += val;
}

inline int query(int pos)
{
    int ans = 0;
    for(; pos >= 1; pos -= (pos & -pos))
        ans += v[pos];
    return ans;
}

int main()
{
    ifstream f("aib.in");
    ofstream g("aib.out");
    f >> n >> q;
    for(int i = 1, x; i <= n; i++)
    {
        f >> x;
        update(i, x);
    }

    while(q--)
    {
        int c, a, b; f >> c >> a;
        if(c < 2)
        {
            f >> b;
            if(!c)
                update(a, b);
            else
                g << query(b) - query(a - 1) << '\n';
        }
        else
        {
            int st = 1, dr = n, m, val, ok = 0;
            while(st <= dr)
            {
                m = (st + dr) >> 1;
                val = query(m);
                if(val == a)
                {
                    ok = 1;
                    g << m << '\n';
                    break;
                }
                else if(val < a)
                    st = m + 1;
                else
                    dr = m - 1;
            }
            if(!ok)
                g << "-1\n";
        }
    }

    f.close();
    g.close();
    return 0;
}