Cod sursa(job #1513268)

Utilizator eu3neuomManghiuc Teodor-Florin eu3neuom Data 29 octombrie 2015 11:03:50
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.69 kb
#include <bits/stdc++.h>

using namespace std;

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

const int NMax = 1e5;
const int BMax = 1e4;

int n;
int Aib[NMax];

int P = BMax - 1;
char Buffer[BMax];
inline void Read(int &x){
    while(!isdigit(Buffer[P])){
        if(++P == BMax){
            fin.read(Buffer, BMax);
            P = 0;
        }
    }
    x = 0;
    while(isdigit(Buffer[P])){
        x = x * 10 + (Buffer[P] - '0');
        if(++P == BMax){
            fin.read(Buffer, BMax);
            P = 0;
        }
    }
}

inline void Update(int pos, const int &x){
    while(pos <= n){
        Aib[pos] += x;
        pos += (pos & (-pos));
    }
}

inline int Query(int pos){
    int sum = 0;
    while(pos > 0){
        sum += Aib[pos];
        pos -= (pos & (-pos));
    }
    return sum;
}

inline int Solve(const int &sum){
    int step = (1 << 20);
    for(int i = 0; step; step >>= 1){
        if(i + step <= n && Query(step + i) == sum){
            return i + step;
        }
        if(i + step <= n && Query(step + i) < sum){
            i += step;
        }
    }
    return -1;
}

int main(){
    int m, type, a, b;
    Read(n); Read(m);
    for(int i = 1; i <= n; i++){
        Read(a);
        Update(i, a);
    }
    for(int i = 1; i <= m; i++){
        Read(type);
        if(type == 0){
            Read(a); Read(b);
            Update(a, b);
        } else {
            if(type == 1){
                Read(a); Read(b);
                fout << Query(b) - Query(a - 1) << "\n";
            } else {
                Read(a);
                fout << Solve(a) << "\n";
            }
        }
    }
    return 0;
}