Cod sursa(job #2819175)

Utilizator ecaterinaEcaterina Stefanescu ecaterina Data 18 decembrie 2021 00:25:16
Problema Arbori indexati binar Scor 0
Compilator c-64 Status done
Runda Arhiva educationala Marime 1.48 kb
#include <stdio.h>

#define NMAX 100001
#define LOGN 17

int v[NMAX];
int aib[NMAX];

int n;

static inline int op(int x) {
    return x & -x;
}

void update(int pos, int val) {
    while (pos <= n) {
        aib[pos] += val;
        pos += op(pos);
    }
}

int search(int value) {
    int pos, step, sum;
    
    sum = 0;
    pos = 0;
    step = 1<<LOGN;
    
    while (step>0) {
        if (pos+step<=n && sum+aib[pos+step]<=value) {
            pos += step;
            sum += aib[pos];
        }
        step/=2;
    }
    return pos;
}

int query(int x) {
    int rez;
    
    rez = 0;
    while (x>0) {
        rez += aib[x];
        x -= op(x);
    }
    
    return rez;
}

int main() {
    FILE *fin, *fout;
    fin = fopen("aib.in", "r");
    fout = fopen("aib.out", "w");
    
    int m, i, q, a, b;
    
    fscanf(fin, "%d%d", &n, &m);
    
    for (i=1; i<=n; i++) {
        fscanf(fin, "%d", &v[i]);
    }
    
    for (i=1; i<=n; i++) {
        aib[i] += v[i];
        if (i+op(i) <= n) {
            aib[i+op(i)] += aib[i];
        }
    }
    
    for (i=0; i<m; i++) {
        fscanf(fin, "%d", &q);
        if (q==0) {
            fscanf(fin, "%d%d", &a, &b);
            update(a, b);
        } else if (q==1) {
            fscanf(fin, "%d%d", &a, &b);
            fprintf(fout, "%d\n", query(b)-query(a-1));
        } else if (q==2) {
            fscanf(fin, "%d", &a);
            fprintf(fout, "%d\n", search(a));
        }
    }
    
    fclose(fin);
    fclose(fout);
    return 0;
}