Cod sursa(job #2230414)

Utilizator Horia14Horia Banciu Horia14 Data 10 august 2018 00:30:29
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.64 kb
#include<cstdio>
#include<cctype>
#define AIB_SIZE 100000
#define BUF_SIZE 1 << 17

int aib[AIB_SIZE+1], n, m, pos = BUF_SIZE;
char buf[BUF_SIZE];

inline char getChar(FILE* fin) {
    if(pos == BUF_SIZE) {
        fread(buf,1,BUF_SIZE,fin);
        pos = 0;
    }
    return buf[pos++];
}

inline int read(FILE* fin) {
    char ch;
    int ans = 0;
    do {
        ch = getChar(fin);
    }while(!isdigit(ch));
    do {
        ans = 10*ans + ch - '0';
        ch = getChar(fin);
    }while(isdigit(ch));
    return ans;
}

inline void updateAIB(int val, int pos) {
    while(pos <= n) {
        aib[pos] += val;
        pos += pos & (-pos);
    }
}

inline int sum(int pos) {
    int s = 0;
    while(pos) {
        s += aib[pos];
        pos &= (pos - 1);
    }
    return s;
}

int binarySearch(int val) {
    int b, e, s, mid, pos;
    b = 1; e = n; pos = -1;
    while(b <= e && pos == -1) {
        mid = (b + e) >> 1;
        s = sum(mid);
        if(s == val)
            pos = mid;
        else if(val > s)
            b = mid + 1;
        else e = mid - 1;
    }
    return pos;
}

int main() {
    int i, op, x, y;
    FILE* fin, *fout;
    fin = fopen("aib.in","r");
    fout = fopen("aib.out","w");
    n = read(fin); m = read(fin);
    for(i = 1; i <= n; i++) {
        x = read(fin);
        updateAIB(x,i);
    }
    for(i = 0; i < m; i++) {
        op = read(fin);
        x = read(fin);
        if(op != 2)
            y = read(fin);
        if(!op)
            updateAIB(y,x);
        else if(op == 1)
            fprintf(fout,"%d\n",sum(y)-sum(x-1));
        else fprintf(fout,"%d\n",binarySearch(x));
    }
    fclose(fin);
    fclose(fout);
    return 0;
}