Cod sursa(job #1208973)

Utilizator andreiiiiPopa Andrei andreiiii Data 16 iulie 2014 21:19:00
Problema Arbori de intervale Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.05 kb
#include <algorithm>
#include <cstdio>
#include <vector>

using namespace std;

class FenwickTree {
public:
    FenwickTree(const int N = 0):
        Size(N),
        Values(vector<int>(N + 1, 0)),
        Tree(vector<int>(N + 1))
        {
            for (int i = 0; i <= N; i++)
                Tree[i] = i;
        }

        int Query(const int left, const int right) const {
            int ret = 0;

            for (int pos = right; pos >= left;)
            {
                int l = pos - (pos & -pos) + 1;

                if (l < left)
                {
                    if (Values[pos] > Values[ret])
                        ret = pos;
                    pos--;
                }
                else
                {
                    if (Values[Tree[pos]] > Values[ret])
                        ret = Tree[pos];
                    pos -= pos & -pos;
                }
            }

            return ret;
        }

        int query(const int left, const int right) const
        {
            return Values[Query(left, right)];
        }

        void update(const int position, const int val)
        {
            Values[position] = val;

            for (int pos = position; pos <= Size; pos += pos & -pos)
            {
                if (Tree[pos] == position)
                {
                    int x = Query(pos - (pos & -pos) + 1, pos - 1);
                    Tree[pos] = Values[pos] > Values[x] ? pos: x;
                }
                else if (Values[position] > Values[Tree[pos]])
                    Tree[pos] = position;
            }
        }
private:
    int Size;
    vector<int> Values, Tree;
};

FenwickTree A;

int main()
{
    freopen("arbint.in", "r", stdin);
    freopen("arbint.out", "w", stdout);

    int N, Q;
    scanf("%d%d", &N, &Q);

    A = FenwickTree(N);
    for (int i = 1; i <= N; i++)
    {
        int x;
        scanf("%d", &x);

        A.update(i, x);
    }

    while (Q--)
    {
        int op, x, y;
        scanf("%d%d%d", &op, &x, &y);

        if (op) A.update(x, y);
        else printf("%d\n", A.query(x, y));
    }
}