Cod sursa(job #1234380)

Utilizator CosminRusuCosmin Rusu CosminRusu Data 27 septembrie 2014 11:59:49
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.49 kb
#include <fstream>
#include <iostream>
#include <vector>
#include <bitset>
#include <string.h>
#include <algorithm>
#include <iomanip>
#include <math.h>
#include <time.h>
#include <stdlib.h>
#include <set>
#include <map>
#include <string>
#include <queue>
#include <deque>

using namespace std;

const char infile[] = "aib.in";
const char outfile[] = "aib.out";

ifstream fin(infile);
ofstream fout(outfile);

const int MAXN = 100005;
const int oo = 0x3f3f3f3f;

typedef vector<int> Graph[MAXN];
typedef vector<int> :: iterator It;

const inline int min(const int &a, const int &b) { if( a > b ) return b;   return a; }
const inline int max(const int &a, const int &b) { if( a < b ) return b;   return a; }
const inline void Get_min(int &a, const int b)    { if( a > b ) a = b; }
const inline void Get_max(int &a, const int b)    { if( a < b ) a = b; }

class BinaryIndexedTree {
private:
    int N;
    vector <int> aib;
    inline int lsb(int x) {
        return x & (-x);
    }
public:
    BinaryIndexedTree() {
    }
    BinaryIndexedTree(int _N) {
        N = _N;
        aib.resize(N + 1, 0);
    }
    void Add(int x, int value) {
        for(int i = x ; i <= N ; i += lsb(i))
            aib[i] += value;
    }
    int Sum(int x) {
        int sum = 0;
        for(int i = x ; i ; i -= lsb(i))
            sum += aib[i];
        return sum;
    }
    int Sum(int x, int y) {
        return Sum(y) - Sum(x - 1);
    }
    int binarySearch(int K) {
        int li = 1, ls = N;
        int ans = -1;
        while(li <= ls) {
            int mid = ((li + ls) >> 1);
            int sum = Sum(mid);
            if(sum == K) {
                ls = mid - 1;
                ans = mid;
                continue;
            }
            if(sum < K)
                li = mid + 1;
            else
                ls = mid - 1;
        }
        return ans;
    }
};

int N, M;

int main() {
    fin >> N >> M;
    BinaryIndexedTree aib(N);
    for(int i = 1 ; i <= N ; ++ i) {
        int x;
        fin >> x;
        aib.Add(i, x);
    }
    for(int i = 1 ; i <= M ; ++ i) {
        int op, x, y;
        fin >> op;
        switch(op) {
            case 0:
                fin >> x >> y;
                aib.Add(x, y);
                break;
            case 1:
                fin >> x >> y;
                fout << aib.Sum(x, y) << '\n';
                break;
            case 2:
                fin >> x;
                fout << aib.binarySearch(x) << '\n';
                break;
        }
    }
    fin.close();
    fout.close();
    return 0;
}