Cod sursa(job #2030737)

Utilizator trifangrobertRobert Trifan trifangrobert Data 2 octombrie 2017 10:04:51
Problema Arbori indexati binar Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 1.64 kb
#include <fstream>
#define DIM 100010

using namespace std;

int n, m;
int a[DIM], aib[DIM];

int Query1(int poz)
{
    int sum = 0;
    for (;poz > 0;poz -= poz & (-poz))
        sum += aib[poz];
    return sum;
}

int Query2(int a)
{
    int left = 1, right = n, mid;
    int poz = -1;
    while(left <= right)
    {
        mid = (left + right) / 2;
        int rez = Query1(mid);
        if(rez == a)
            poz = mid;
        if (rez > a)
            right = mid - 1;
        else
            left = mid + 1;
    }
    return poz;
}

void Update(int poz, int val)
{
    int x = poz;
    while(poz <= n)
    {
        aib[poz] += val;
        poz += poz & (-poz);
    }
    a[x] += val;
}

int main()
{
    ifstream f("aib.in");
    ofstream g("aib.out");
    f >> n >> m;
    for (int i = 1;i <= n;++i)
    {
        f >> a[i];
        Update(i, a[i]);
    }
    for (int i = 1;i <= m;++i)
    {
        int cod;
        f >> cod;
        switch(cod)
        {
            case 0:
            {
                int poz, val;
                f >> poz >> val;
                Update(poz, val);
                break;
            }
            case 1:
            {
                int x, y;
                f >> x >> y;
                x = Query1(x - 1);
                y = Query1(y);
                g << y - x << "\n";
                break;
            }
            case 2:
            {
                int k;
                f >> k;
                g << Query2(k) << "\n";
                break;
            }
        }
    }
    f.close();
    g.close();
    return 0;
}