Cod sursa(job #2571779)

Utilizator dimi999Dimitriu Andrei dimi999 Data 5 martie 2020 10:08:27
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.75 kb
#include <bits/stdc++.h>

using namespace std;

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

int pw = 1, n;

struct Aib
{
    int v[100005];

    void update(int add, int poz)
    {
        for(int i = poz; i <= n; i += i & (-i))
            v[i] += add;
    }

    int query(int poz)
    {
        int ans = 0;

        for(int i = poz; i >= 1; i -= i & (-i))
            ans += v[i];

        return ans;
    }

    int rez(int sum)
    {
        int pas = pw, i = 0;
        bool ok = false;

        while(pas >= 1)
        {
            if(sum > v[i+pas])
            {
                sum -= v[i+pas];
                i += pas;
            }
            else
                if(sum == v[i+pas])
                {
                    //sum = 0;
                    ok = true;
                }
             pas /= 2;
             while(i + pas > n && pas >= 1)
                pas /= 2;
        }

        if(ok == true)
            return i + 1;
        else
            return -1;
    }
}aib;


int main()
{
    int m;

    fin >> n >> m;

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

    while(pw <= n)
        pw *= 2;
    pw /= 2;

    for(int i = 1; i <= m; i++)
    {
        int stare;

        fin >> stare;

        if(stare == 2)
        {
            int x;

            fin >> x;

            fout << aib.rez(x) << '\n';


        }
        else
        {
            int x, y;

            fin >> x >> y;

            if(stare == 0)
                aib.update(y,x);
            else
                fout << aib.query(y) - aib.query(x-1) << '\n';
        }
    }




    return 0;
}