Cod sursa(job #3213737)

Utilizator tomaionutIDorando tomaionut Data 13 martie 2024 13:21:42
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.31 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 val)
{
    while (x <= n)
    {
        aib[x] += val;
        x += (x & (-x));
    }
}

int Query(int x)
{
    int s = 0;
    while (x >= 1)
    {
        s += aib[x];
        x -= (x & (-x));
    }
    return s;
}

int CautBin(int x)
{
    int st = 1, dr = n, mij, sol = -1, y, ok = 0;
    while (st <= dr)
    {
        mij = (st + dr) / 2;
        y = Query(mij);
        if (y >= x)
        {
            if (y == x)
                ok = 1;
            sol = mij;
            dr = mij - 1;
        }
        else st = mij + 1;
    }
    if (ok == 0)
        return -1;
    else return sol;
}

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

    while (m--)
    {
        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";
        }
    }

    return 0;
}