Cod sursa(job #2289280)

Utilizator SqueekDanielTodasca Daniel SqueekDaniel Data 24 noiembrie 2018 12:39:25
Problema Arbori indexati binar Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.32 kb
#include <bits/stdc++.h>

#define Zeros(X) X&(-X)
#define MAXN     100005

int N, M;
int AIB[MAXN];

void Update(int X, int Value) {
    for (X; X<=N; X += Zeros(X))
        AIB[X] += Value;
}

int Query(int X) {
    int Sum = 0;
    for (X; X; X -= Zeros(X))
        Sum += AIB[X];
    return Sum;
}

std::ifstream In("sequencequery.in");
std::ofstream Out("sequencequery.out");

int FindPos(int Sum) {
    int Left = 1, Right = N,
        Middle, aux;

    while (Left <= Right) {
        Middle = (Left+Right)/2;
        aux = Query(Middle);

        if (aux == Sum) return Middle;
        else if (aux < Sum)
            Left = Middle+1;
        else
            Right = Middle-1;
    }   return -1;
}

void Citire() {
    In >> N >> M;
    for (int i=1, Value; i<=N; ++i)
        In >> Value,
        Update(i, Value);
}

void Rezolvare() {
    int Type, X, Y;
    for (int i=0; i<M; ++i) {
        In >> Type;

        if (Type == 0) {
            In >> X >> Y;
            Update(X, Y);
        }   else
        if (Type == 1) {
            In >> X >> Y;
            Out << Query(Y) - Query(X-1) << '\n';
        }
        else {
            In >> X;
            Out << FindPos(X) << '\n';
        }
    }
}

int main()
{
    Citire();
    Rezolvare();

    return 0;
}