Cod sursa(job #1306118)

Utilizator gabrieligabrieli gabrieli Data 30 decembrie 2014 16:13:38
Problema Arbori indexati binar Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.98 kb
//#include <fstream>
#include <cstdio>
#include <vector>
using namespace std;

inline
int next(const int x) {
    int i = 0;
    while (x && !(x & (1 << i))) ++i;
    return x + (1 << i);
}

inline
int prev(const int x) {
    int i = 0;
    while (x && !(x & (1 << i))) ++i;
    return x - (1 << i);
}

void update(int i, int x, vector<int>& aib) {  // operation 0
    for (; i < aib.size(); i = next(i))
        aib[i] += x;
}

int prefixSum(int i, const vector<int>& aib) {  // operation 1
    int sum = 0;
    for (; i; i = prev(i)) sum += aib[i];
    return sum;
}

inline
int search(int sum, const vector<int>& aib) {  // operation 2
    int li = 1, ls = aib.size(), midd;
    
    while (li < ls) {
        midd = li + (ls - li) / 2;
        if (prefixSum(midd, aib) < sum)
            li = midd + 1;
        else
            ls = midd;
    }
    
    return (li < aib.size() && prefixSum(li, aib) == sum) ? li : -1;    
}

int main() {
    //ifstream fin("aib.in");
    //ofstream fout("aib.out");
    FILE *in = fopen("aib.in", "r");
    FILE *out = fopen("aib.out", "w");
        
    int n, m;
    //fin >> n >> m;
    fscanf(in, "%d %d", &n, &m);
    vector<int> aib(n+1, 0);
    
    for (int x, i = 1; n; --n, ++i) {
        //fin >> x;
        fscanf(in, "%d", &x);
        update(i, x, aib);
    }
    
    for (int op, a, b; m; --m) {
        //fin >> op;
        fscanf(in, "%d", &op);
        if (op == 0) {
            //fin >> a >> b;
            fscanf(in, "%d %d", &a, &b);
            update(a, b, aib);
        }
        else if (op == 1) {
            //fin >> a >> b;
            //fout << prefixSum(b, aib) - prefixSum(a - 1, aib) << '\n';
            fscanf(in, "%d %d", &a, &b);
            fprintf(out, "%d\n", prefixSum(b, aib) - prefixSum(a - 1, aib));        
        }
        else {
            //fin >> a;
            //fout << search(a, aib) << '\n';	
            fscanf(in, "%d", &a);
            fprintf(out, "%d\n", search(a, aib));
        }
    }
    
    fclose(in);
    return 0;
}