Cod sursa(job #1870179)

Utilizator Tomi98Osvath Tamas Tomi98 Data 6 februarie 2017 14:15:02
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.14 kb
#include <fstream>
#define dim 100001
#define zeros(x) ( (x ^ (x - 1)) & x )

using namespace std;

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

int AIB[dim], n, m;

void update(int poz, int x){
    for (int i = poz; i <= n; i += zeros(i))
        AIB[i] += x;
}

int query(int x){
    int s = 0;
    for (int i = x; i >= 1; i -= zeros(i))
        s += AIB[i];
    return s;
}

int find(int x){
   int st = 0;
   int dr = n + 1;
   int mij;
   while(dr - st > 1){
     mij = st + (dr - st) / 2;
     if(query(mij) >= x) dr = mij;
       else st = mij;
   }
   if(query(dr) != x) return -1;
     else return dr;
}

int main()
{
    fin >> n >> m;
    int x, y;
    for (int i = 1; i <= n; i++){
        fin >> x;
        update(i, x);
    }
    while (m --){
        int t;
        fin >> t;
        if (t == 0){
            fin >> x >> y;
            update(x, y);
        }
        else if (t == 1){
            fin >> x >> y;
            fout << query(y) - query(x - 1) << '\n';
        }
        else{
            fin >> x;
            fout << find(x) << '\n';
        }
    }
    return 0;
}