Cod sursa(job #2172916)

Utilizator andreigeorge08Sandu Ciorba andreigeorge08 Data 15 martie 2018 19:01:12
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.29 kb
#include <bits/stdc++.h>

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

int n, m, aib[100005];

void Update(int x, int y)
{
    for(int i = x; i <= n; i += (i & (-i)))
        aib[i] += y;
}

long long Query(int x)
{
    long long sum = 0;
    for(int i = x; i >= 1; i -= (i & (-i)))
        sum += aib[i];
    return sum;
}

int CautBin(int x)
{
    int st = 1, dr = n, mij, poz = -1;

    while(st <= dr)
    {
        mij = (st + dr) / 2;
        int val = Query(mij);

        if(val == x)
        {
            poz = mij;
            dr = mij - 1;
        }
        else if(val > x) dr = mij - 1;
        else st = mij + 1;
    }

    return poz;
}

void Citire()
{
    int x, y, op;
    fin >> n >> m;
    for(int i = 1; i <= n; i++)
    {
        fin >> x;
        Update(i, x);
    }

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

        if(op == 0)
        {
            fin >> x >> y;
            Update(x, y);
        }
        else if(op == 1)
        {
            fin >> x >> y;
            fout << Query(y) - Query(x - 1) << "\n";
        }
        else
        {
            fin >> x;
            fout << CautBin(x) << "\n";
        }
    }
}
int main()
{
    Citire();
    return 0;
}