Cod sursa(job #2849125)

Utilizator XyanEusebiu Pusca Xyan Data 14 februarie 2022 16:51:50
Problema Arbori de intervale Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.21 kb

#include <iostream>
#include <fstream>
#include <vector>
#include <deque>
using namespace std;
ifstream fin("arbint.in");
ofstream fout("arbint.out");
struct st {
    int nmax;
    int l, r;
    st* f = NULL, *sub1 = NULL, *sub2 = NULL;
};
vector <pair <int, st*> > v;
st* r = new st;
int N, M;

int gen(int l, int r, st *f, bool dir)
{
    st* x = new st;
    x->l = l;
    x->r = r;
    x->f = f;
    int mid = (l + r) / 2;
    if (dir)
        f->sub2 = x;
    else
        f->sub1 = x;
    if (r == l)
    {
        x->nmax = v[l].first;
        v[l].second = x;
        return v[l].first;
    }
    int val1 = gen(l, mid, x, 0);
    int val2 = gen(mid + 1, r, x, 1);
    x->nmax = max(val1, val2);
    return x->nmax;
}

int query(int l, int r, st *a)
{
    if (l == a->l && r == a->r) {
        return a->nmax;
    }
    int mid = (a->l + a->r) / 2;
    if (r <= mid) return query(l, r, a->sub1);
    if (l > mid) return query(l, r, a->sub2);
    return max((l == a->l ? a->sub1->nmax : query(l, mid, a->sub1)), (r == a->r ? a->sub2->nmax : query(mid + 1, r, a->sub2)));
}

void update(st *a)
{
    if (a->f != NULL)
    {
        a->nmax = max(a->sub1->nmax, a->sub2->nmax);
        update(a->f);
    }
}

void display()
{
    deque <st*> q;
    q.push_front(r->sub1);
    int d = 1;
    int tm = 1;
    while (!q.empty())
    {
        if (q.back()->sub1 != NULL)
            q.push_front(q.back()->sub1);
        if (q.back()->sub2 != NULL)
            q.push_front(q.back()->sub2);
        q.pop_back();
        tm--;
        if (!tm)
        {
            d *= 2;
            tm = d;
        }
    }
}

int main()
{

    fin >> N >> M;
    int x, y;
    bool o;
    for (int i = 0; i < N; i++)
    {
        pair <int, st*> a;
        fin >> a.first;
        v.push_back(a);
    }
    r->nmax = gen(0, N-1, r, 0);
    display();
    for (int i = 0; i < M; i++)
    {
        fin >> o >> x >> y;
        if (o)
        {
            v[x - 1].first = y;
            v[x - 1].second->nmax = y;
            update(v[x - 1].second->f);
        }

        else
            fout << query(x - 1, y - 1, r->sub1) << endl;
    }
    return 0;
}