Cod sursa(job #2999539)

Utilizator iProgramInCppiProgramInCpp iProgramInCpp Data 11 martie 2023 10:16:12
Problema Arbori indexati binar Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.12 kb
#include <iostream>
#include <fstream>
using namespace std;
ifstream fin ("aib.in");
ofstream fout("aib.out");

int aib[100001], n;

int thing(int x)
{
    /// example
    /// x  = b101100100
    /// x-1= b101100011 = y
    /// x^y= b000000111 = z
    /// z&x= b000000100

    return (x ^ (x - 1)) & x;
}

void Add(int pos, int val)
{
    for (int i = pos; i <= n; i += thing(i))
        aib[i] += val;
}

int Query(int pos)
{
    int x = 0;
    for (int i = pos; i > 0; i -= thing(i))
        x += aib[i];
    return x;
}

int Query2(int a)
{
    for (int i=1; i<=n; i++)
    {
        int q = Query(i);
        if (q == a) return i;
        if (q > a) return -1;
    }
    return -1;
}

int main()
{
    int m;
    fin >> n >> m;
    for (int i=1; i<=n; i++)
    {
        int a;
        fin >> a;
        Add(i, a);
    }

    for (int i=1; i<=m; i++)
    {
        int x,a,b=0;
        fin >> x >> a; if (x != 2) fin >> b;

        if(x==0) Add(a,b);
        if(x==1) fout << Query(b) - Query(a - 1) << '\n';
        if(x==2) fout << Query2(a) << '\n';
    }


    return 0;
}