Cod sursa(job #2449172)

Utilizator PatrickCplusplusPatrick Kristian Ondreovici PatrickCplusplus Data 18 august 2019 14:28:22
Problema Arbori de intervale Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.86 kb
#include <fstream>
#define NMAX 100000

using namespace std;

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

int n, m, v[NMAX + 4];
int aint[NMAX * 2 + 1]; // Space complexity = O(NMAX * 2) pentru ca inaltimea arborelui este log2N, deci avem 1 + 2 + .... + 2^(log2N) noduri = 2 * 2^(log2N) - 1 noduri (formula de la progresii geometrice)
void Build(); // Time complexity = O(N)
void Update(); // Time complexity = O(log2N) pentru ca are un path unic pana la radacina
void Query(); // time complexity = O(log2N) pentru ca la fiecare nivel al inaltimii o sa ne extindem maxim pe 2 noduri deci O(2 * log2N) = O(log2N)

void Build(int nod, int st, int dr)
{
    if (st == dr)
    {
        aint[nod] = v[st];
        return;
    }
    int mid = (st + dr) / 2;
    Build(nod * 2, st, mid);
    Build(nod * 2 + 1, mid + 1, dr);
    aint[nod] = max(aint[nod * 2], aint[nod * 2 + 1]);
}

int Query(int nod, int st, int dr, int a, int b)
{
    if (st >= a && dr <= b)
        return aint[nod];
    if (st > b || dr < a)
        return -(1 << 30);
    int mid = (st + dr) / 2;
    return max(Query(nod * 2, st, mid, a, b), Query(nod * 2 + 1, mid + 1, dr, a, b));
}

void Update(int nod, int st, int dr, int poz, int val)
{
    if (st > poz || dr < poz) return;
    if (st == dr && st == poz)
    {
        aint[nod] = val;
        return;
    }
    int mid = (st + dr) / 2;
    Update(nod * 2, st, mid, poz, val);
    Update(nod * 2 + 1, mid + 1, dr, poz, val);
    aint[nod] = max(aint[nod * 2], aint[nod * 2 + 1]);
}

int main()
{
    fin >> n >> m;
    for (int i = 1; i <= n; ++i)
        fin >> v[i];
    Build(1, 1, n);
    while (m--)
    {
        int p, a, b;
        fin >> p >> a >> b;
        if (p == 0)
            fout << Query(1, 1, n, a, b) << "\n";
        else
            Update(1, 1, n, a, b);
    }
    return 0;
}