Cod sursa(job #1527008)

Utilizator diana-t95FMI Tudoreanu Diana Elena diana-t95 Data 17 noiembrie 2015 19:27:58
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.19 kb
#include <iostream>
#include <fstream>

using namespace std;
#define maxn 100100

int n, m, aib[maxn];

void update(int pos, int value)
{
    for (;pos <= n; pos += (pos&(-pos)))
    {
        aib[pos] += value;

    }
}
int query(int pos)
{
    int answer = 0;
    for (;pos>=1; pos-= (pos&(-pos)))
    {
        answer += aib[pos];
    }
    return answer;
}
int search_b(int value)
{
    int pos, st = 1, dr = n, ans;
    while (st < dr) {
        pos = (st+dr)/2;
       ans = query(pos);
    if (ans >= value) dr = pos;
    else st = pos+1;
    }
    ans = query(st);
    if (ans == value) return st;
    return -1;
}
int main()
{
    ifstream f("aib.in");
    ofstream g("aib.out");
    f>>n>>m;
    int op, b, c;
    for (int i = 1; i <= n; i++)
    {
        f>>b;
        update(i, b);
    }

    for (int i = 1; i <= m; i++)
    {
        f>>op;
        if (op == 0)
        {
            f>>b>>c;
            update(b,c);
        }
        if (op == 1)
        {
            f>>b>>c;
            g<<query(c)-query(b-1)<<'\n';
        }
        if (op == 2)
        {
            f>>b;
            g<<search_b(b)<<'\n';
        }
    }
}