Cod sursa(job #2418165)

Utilizator AlexNeaguAlexandru AlexNeagu Data 3 mai 2019 21:55:55
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.68 kb
#include <fstream>
#define nmax 200000
#define complement(x) x&(-x)

using namespace std;

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

int Fenwick_Tree [nmax] , n, m, operation, position_left, position_right, x, value;

void Tree_Update (int position, int updated_value)
{
    while (position <= n)
    {
        Fenwick_Tree [position] += updated_value;
        position += complement(position);
    }
}
int Query(int position)
{
    int sum = 0;
    while (position)
    {
       sum += Fenwick_Tree [position];
       position -= complement(position);
    }
   return sum;
}
int Search_For (int value)
{
    int left_position = 1;
    int right_position = n;
    while (left_position <= right_position)
    {
        int mid = (left_position + right_position) / 2;
        int sum = Query(mid);
        if (sum > value)
        right_position = mid - 1;
        else if (sum < value)
        left_position = mid + 1;
        else if (sum == value)
        return mid;
    }

   return -1;
}
int main()
{
    ios_base::sync_with_stdio(false);

    fin >> n >> m;
    for (int i = 1; i <= n; i++)
    {
        fin >> x;
        Tree_Update (i, x);
    }
    for (int i = 1; i <= m; i++)
    {
        fin >> operation;
        if (operation <= 1)
        {
            fin >> position_left >> position_right;
            if (!operation)
            Tree_Update (position_left, position_right);
            else fout << (Query (position_right) - Query (position_left - 1)) << "\n";
        }
        if (operation == 2)
        {
           fin >> value;
           fout << ( Search_For (value) ) << "\n";
        }
    }
    return 0;
}