Cod sursa(job #2533357)

Utilizator rares404AlShaytan - Balasescu Rares rares404 Data 28 ianuarie 2020 22:16:50
Problema Arbori indexati binar Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.93 kb
#include <bits/stdc++.h>

const int MV = 1e5 ;

class BinaryIndexedTree {
private :
        int aib[MV + 5] ;
        int sz ;
public :
        BinaryIndexedTree(int _ = 0) {
                this ->sz = _ ;
        }
        void update(int poz, int val) {
                for (int i = poz ; i <= sz ; i += (i & -i)) {
                        aib[i] += val ;
                }
        }
        int query(int poz) {
                int ret(0) ;
                for (int i = poz ; i > 0 ; i -= (i & -i)) {
                        ret += aib[i] ;
                }
                return ret ;
        }
        int BinarySearch(int val) {
                int ret(0), cv(val) ;
                for (int step(1 << 28) ; step && val ; step >>= 1) {
                        if (ret + step <= sz && aib[ret + step] < val) {
                                val -= aib[ret + step] ;
                                ret |= step ;
                        }
                }
                return ret + 1 ;
                return -1 ;
        }
};

int v[MV + 5] ;

int main() {
        int n, m ;
        freopen("aib.in", "r", stdin) ;
        freopen("aib.out", "w", stdout) ;
        std::cin >> n >> m ;
        BinaryIndexedTree aib(n) ;
        int val, type, a, b ;
        for (int i = 1 ; i <= n ; ++ i) {
                std::cin >> v[i] ;
                aib.update(i, v[i]) ;
        }
        for (int i = 1 ; i <= m ; ++ i) {
                std::cin >> type ;
                if (type == 0) {
                        std::cin >> a >> b ;
                        aib.update(a, b) ;
                } else if (type == 1) {
                        std::cin >> a >> b ;
                        std::cout << aib.query(b) - aib.query(a - 1) << '\n' ;
                } else {
                        std::cin >> a ;
                        std::cout << aib.BinarySearch(a) << '\n' ;
                }
        }
}