Cod sursa(job #3374772)

Utilizator AlexZeuVasile Alexandru AlexZeu Data 9 noiembrie 2026 11:29:15
Problema Datorii Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.74 kb
#include <fstream>
#include <iostream>
#include <vector>

template<typename T>
class fenwick_tree
{
public:
   const size_t tree_size;

   /* Indexed from 1. */
   std::vector<T> arr;

public:
   fenwick_tree(const std::vector<T>& from_arr) :
       tree_size{from_arr.size()}, arr(from_arr.size() + 1, 0)
   {
       for (size_t i{}; i < tree_size; i++) {
           size_t update_index = i + 1;

           while (update_index <= tree_size) {
               arr[update_index] += from_arr[i];
               update_index += update_index & (-update_index);
           }
       }
   }

   void update(const size_t index, const T& ov, const T& nv)
   {
       size_t update_index = index;
       while (update_index <= tree_size) {
           arr[update_index] -= nv;
           update_index += update_index & (-update_index);
       }
   }

   T __get_range(const size_t a)
   {
       T sum{};
       size_t current_level = a;

       while (current_level > 0) {
           sum += arr[current_level];
           current_level -= (current_level & -current_level);
       }

       return sum;
   }

   T query(const size_t l, const size_t r)
   {
        T result{};

        result = __get_range(r) - __get_range(l);

        return result;
   }

};

int main() {
    std::ifstream fin("datorii.in");
    std::ofstream fout("datorii.out");

    int N, M;
    fin >> N >> M;
    
    std::vector<int> values(N);

    for (int &e: values)
        fin >> e;
    
    fenwick_tree<int> ft(values);

    int c, e1, e2;
    while (M--) {
        fin >> c >> e1 >> e2;
        if (c == 0) {
            ft.update(e1, values[e1 - 1], e2);
            values[e1 - 1] -= e2;
        } else {
            fout << ft.query(e1, e2) + values[e1 - 1] << "\n";
        }
    }

    return 0;
}