Cod sursa(job #780808)

Utilizator a_h1926Heidelbacher Andrei a_h1926 Data 21 august 2012 22:00:44
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.24 kb
#include <cstdio>

using namespace std;

const int kMaxN = 100005;

int N, BIT[kMaxN];

inline int LSB(const int X) {
    return (X&(-X));
}

inline void Update(int X, const int V) {
    for (; X <= N; X += LSB(X))
        BIT[X] += V;
}

inline int Query(int X) {
    int S=0;
    for (; X > 0; X -= LSB(X))
        S+=BIT[X];
    return S;
}

inline int Search(int V)
{
    int Step;
    for (Step = 1; Step < N; Step <<= 1);
    for(int i = 0; Step; Step >>= 1) {
        if (i+Step <= N && V >= BIT[i+Step]) {
            i += Step, V -= BIT[i];
            if (!V)
                return i;
        }
    }
    return -1;
}

int main() {
    freopen("aib.in", "r", stdin);
    freopen("aib.out", "w", stdout);
    int M; scanf ("%d %d", &N, &M);
    for (int i=1; i<=N; ++i) {
        int V; scanf("%d", &V);
        Update(i, V);
    }
    for (; M>0; --M) {
        int Type, X, Y;
        scanf("%d %d", &Type, &X);
        if (Type==0) {
            scanf("%d", &Y);
            Update(X, Y);
        }
        if (Type==1) {
            scanf("%d", &Y);
            printf("%d\n", Query(Y)-Query(X-1));
        }
        if (Type==2)
            printf("%d\n", Search (X));
    }
    return 0;
}