Cod sursa(job #2325173)

Utilizator Horia14Horia Banciu Horia14 Data 22 ianuarie 2019 01:18:54
Problema Arbori indexati binar Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.61 kb
#include<cstdio>
#include<cctype>
#define aib_SIZE 100000
using namespace std;

int aib[aib_SIZE+1], n, m;

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

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

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

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

int binarySearch(int x) {
    int st, dr, mij, poz, val;
    st = 1, dr = n, poz = -1;
    while(st <= dr && poz == -1) {
        mij = (st + dr) >> 1;
        val = sumQuery(mij);
        if(x == val)
            poz = mij;
        else if(x < val)
            dr = mij - 1;
        else st = mij + 1;
    }
    return poz;
}

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