Cod sursa(job #1903060)

Utilizator medicinedoctoralexandru medicinedoctor Data 4 martie 2017 22:50:33
Problema Arbori indexati binar Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.87 kb
#include <fstream>
#include <vector>
#include <cmath>

using namespace std;

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

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

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

    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 (i < q.size() && w + q[i] < x) w += q[i], i++;
            if (i < q.size() && w + q[i] == x) w += q[i], j = a[i].size();

            while (j < a[i].size() && w + a[i][j] < x) w += a[i][j], j++;
            if (j < a[i].size() && w + a[i][j] == x) w += a[i][j], j++;

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

    return 0;
}