Cod sursa(job #1376636)

Utilizator Al3ks1002Alex Cociorva Al3ks1002 Data 5 martie 2015 18:08:30
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.78 kb
#include<cstdio>
#include<fstream>
#include<iostream>
#include<iomanip>
#include<algorithm>
#include<vector>
#include<bitset>
#include<deque>
#include<queue>
#include<set>
#include<map>
#include<cmath>
#include<cstring>
#include<ctime>
#include<cstdlib>
#include<unordered_map>

#define ll long long
#define pb push_back
#define mp make_pair
#define pii pair<int,int>
#define pll pair<ll,ll>
#define all(x) (x).begin(), (x).end()
#define fi first
#define se second

using namespace std;

const int nmax = 100005;

int n, q, i, x, lim, op, poz, val, a, b, aib[nmax];

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

int sum(int poz)
{
    int r = 0;

    for(int i = poz; i; i -= i & (-i))
        r += aib[i];

    return r;
}

int query(int val)
{
    int x = val;
    int poz = 0;

    for(int step = lim; step; step /= 2)
        if(poz + step < n && aib[poz + step] < x)
        {
            x -= aib[poz + step];
            poz += step;
        }

    if(sum(poz + 1) == val) return poz + 1;
    return -1;
}

int main()
{
    freopen("aib.in", "r", stdin);
    freopen("aib.out", "w", stdout);

    scanf("%d%d", &n, &q);

    for(i = 1; i <= n; i++)
    {
        scanf("%d", &x);
        update(i, x);
    }

    for(lim = 1; lim <= n; lim *= 2);

    for(; q; q--)
    {
        scanf("%d", &op);

        if(op == 0)
        {
            scanf("%d%d", &poz, &val);
            update(poz, val);
        }
        else if(op == 1)
        {
            scanf("%d%d", &a, &b);
            printf("%d\n", sum(b) - sum(a - 1));
        }
        else
        {
            scanf("%d", &a);
            printf("%d\n", query(a));
        }
    }

    return 0;
}