Cod sursa(job #1649157)

Utilizator blue_skyPetrica Stefan Cosmin blue_sky Data 11 martie 2016 12:41:44
Problema Arbori indexati binar Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 1.22 kb
#include <fstream>
#define DIM 100001

using namespace std;

int n, m, t, x, y, arb[DIM];

int zeros(int x)
{
    return (x ^ (x-1)) & x;
}

void update(int poz, int val)
{
    for(int i = poz; i <= n; i += zeros(i))
        arb[i] += val;
}

int calc(int poz)
{
    int s = 0;
    for(int i = poz; i >0; i -= zeros(i))
        s += arb[i];
    return s;
}

int main()
{
    ifstream f("aib.in");
    ofstream g("aib.out");

    f >> n >> m;

    for(int i = 1; i <= n; ++i)
    {
        f >> x;
        update(i, x);
    }
    for(int i = 1; i <= m; ++i)
    {
        f >> t;
        if(t == 0)
        {
            f >> x >> y;
            update(x, y);
        }
        else if(t == 1)
        {
            f >> x >> y;
            g << calc(y) - calc(x - 1) << '\n';
        }
        else
        {
            bool ok = 1;
            f >> x;
            for(int j = 1; j <= n; ++j)
            {
                if(calc(j) == x)
                {
                    g << j << '\n';
                    ok = 0;
                    break;
                }
            }
            if(ok) g << "-1\n";
        }
    }
    f.close();
    g.close();
    return 0;
}