Cod sursa(job #2777921)

Utilizator francescom_481francesco martinut francescom_481 Data 26 septembrie 2021 10:26:35
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.3 kb
#include<bits/stdc++.h>

using namespace std;

ifstream fin("aib.in");
ofstream fout("aib.out");
#define cin fin
#define cout fout

#define N 100005
int aib[N], n, m, cerinta, a, b, x;

void update(int poz,int val)
{
    for( ; poz <= n ; poz += poz&(-poz))
    {
        aib[poz] += val;
    }
}
int query(int poz)
{
    int s = 0;
    for(; poz > 0 ; poz -= poz&(-poz))
    {
        s += aib[poz];
    }
    return s;
}
int caut(int a)
{
    int pw = 1;
    while(pw <= n)pw <<= 1;
    pw >>= 1;
    int pos = 0;
    while(pw != 0)
    {
        if(pos+pw <= n)
        {
            int x = query(pos+pw);
            if(x == a)return pos+pw;
            else if(x < a)pos += pw;
        }
        pw >>= 1;
    }
    return -1;
}

int main()
{
    cin >> n >> m;
    for(int i = 1 ; i <= n ; i++)
    {
        cin >> x;
        update(i,x);
    }
    for(int i = 1 ; i <= m ; i++)
    {
        cin >> cerinta;
        if(cerinta == 0)
        {
            cin >> a >> b;
            update(a,b);
        }
        else if(cerinta == 1)
        {
            cin >> a >> b;
            cout << query(b) - query(a-1) << '\n';
        }
        else
        {
            cin >> a;
            cout << caut(a) << '\n';
        }
    }
    return 0;
}