Cod sursa(job #1502131)

Utilizator alexandru.ghergutAlexandru-Gabriel Ghergut alexandru.ghergut Data 14 octombrie 2015 11:09:13
Problema Datorii Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.95 kb
#include <fstream>
#include <cmath>
using namespace std;

int nextInt(string &line, unsigned long long &pos)
{
    if (pos < line.size())
    {
        int n = 0;
        while (line[pos] != ' ' && line[pos] != '\n')
            n = n * 10 + (line[pos++] - '0');
        pos++;
        return n;
    }

    return -1;
}

void update(int index, int val, int pos, int left, int right, int A[], int tree[])
{
    if (left == right && pos == left)
        tree[index] += val;
    else if (pos >= left && pos <= right)
    {
        update(index * 2 + 1, val, pos, left, (left + right) / 2, A, tree);
        update(index * 2 + 2, val, pos, (left + right) / 2 + 1, right, A, tree);

        tree[index] += val;
    }
}

int query(int index, int left, int right, int cLeft, int cRight, int A[], int tree[])
{
    if (left <= cLeft && right >= cRight)
        return tree[index];

    if (cLeft > right || cRight < left)
        return 0;

    int leftSum = query(index * 2 + 1, left, right, cLeft, (cLeft + cRight) / 2, A, tree);
    int rightSum = query(index * 2 + 2, left, right, (cLeft + cRight) / 2 + 1, cRight, A, tree);

    return leftSum + rightSum;
}

int main()
{
    int i, N, M;
    unsigned long long pos = 0;
    string line;
    ifstream f("datorii.in");
    getline(f, line, '~');
    line += ' ';
    N = nextInt(line, pos);
    M = nextInt(line, pos);
    int A[N], length = (1 << ((int)log2(N) + 2)) - 1;
    int tree[length];
    fill(tree, tree + length, 0);
    for (i = 0; i < N; i++)
    {
        A[i] = nextInt(line, pos);
        update(0, A[i], i, 0, N - 1, A, tree);
    }

    int op, x, y;
    ofstream g("datorii.out");
    for (i = 0 ; i < M; i++)
    {
        op = nextInt(line, pos);
        x = nextInt(line, pos);
        y = nextInt(line, pos);
        if (op == 0)
            update(0, -y, x - 1, 0, N - 1, A, tree);
        else if (op == 1)
            g << query(0, x - 1, y - 1, 0, N - 1, A, tree) << '\n';
    }
    f.close();
    g.close();
    return 0;
}