Cod sursa(job #3267176)

Utilizator BogaBossBogdan Iurian BogaBoss Data 11 ianuarie 2025 10:12:00
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.21 kb
#include <bits/stdc++.h>

using namespace std;

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

int n;
int aib[100005];

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

void create()
{
    for(int i = 1; i<=n; i++)
    {
        int x;
        fin >> x;
        update(i,x);
    }
}

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

int cb(int x)
{
    int st = 1, dr = n;
    while(st < dr)
    {
        int mij = (st + dr)/2;
        int s = query(mij);
        if(s >= x)
            dr = mij;
        else
            st = mij + 1;
    }
    if(query(st) != x)
        return -1;
    return st;
}

int main()
{
    int m;
    fin >> n >> m;
    create();
    for(int i = 1; i<=m; i++)
    {
        int c, x, y;
        fin >> c >> x;
        if(c == 0)
        {
            fin >> y;
            update(x, y);
        }
        else if(c == 1)
        {
            fin >> y;
            fout << query(y) - query(x-1) << '\n';
        }
        else if(c == 2)
        {
            fout << cb(x) << '\n';
        }
    }
    return 0;
}