Cod sursa(job #1902253)

Utilizator medicinedoctoralexandru medicinedoctor Data 4 martie 2017 14:42:08
Problema Arbori indexati binar Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.88 kb
#include <fstream>
#include <vector>
#include <cmath>
//#include <iostream>

using namespace std;

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

vector <vector <int> > a;
vector <long long> q;

int main()
{
    int n, m, c, x, y, s;
    fin >> n >> m;
    s = sqrt(n) + 1;
    a.resize(s + 10);
    q.resize(s + 10);

    for (int i = 0; i < n; i++)
    {
        fin >> x ;
        a[i / s].push_back(x);
    }

    for (int i = 0; i < q.size(); i++)
    {
        int w = 0;
        for (int j = 0; j < a[i].size(); j++)
            w += a[i][j];
        q[i] = w;
    }

    for (int i = 0; i < m; i++)
    {
        fin >> c >> x ;
        if (c != 2) fin >> y;
        if (c == 0)
        { // a[x] += y;
            x--;
            a[x / s] [x % s] += y;
            q[x / s] += y;
        }
        if (c == 1)
        { // suma i = x -> y
            x--; y--;

            int w = 0;

            if (x / s == y / s)
            {
                for (int i = x % s; i < y % s + 1; i++) w += a[x / s][i];
            }
            else
            {
                for (int i = x % s; i < a[x / s] .size(); i++) w += a[x / s][i];

                for (int i = 1 + x / s; i < y / s; i++) w += q[i];

                for (int i = 0; i < y % s + 1; i++) w += a[y / s][i];

            }

            cout << w << '\n';
        }
        if (c == 2)
        {//primele k elemente cu suma x
            int w = 0, i = 0, j = 0;

            while (w + q[i] < x) w += q[i], i++;
            if (w + q[i] == x) w += q[i], i++, j = -1;

            if (j != -1)
                while (w + a[i][j] < x) w += a[i][j], j++;
            else j = s - 1;
            if (w + a[i][j] == x) w += a[i][j], j++;

            if (w == x) cout << (i - 1) * s + j + 1 << '\n';
            else cout << "-1\n";
        }
    }

    return 0;
}