Cod sursa(job #2393911)

Utilizator HerddexJinga Tudor Herddex Data 1 aprilie 2019 10:42:52
Problema Arbori de intervale Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.56 kb
#include <fstream>
using namespace std;
ifstream fin("arbint.in");
ofstream fout("arbint.out");
const int maxN = 100005;

struct nod{
    int info = -1;
    int leftBound = -1, rightBound = -1;
}undefined;

int V[maxN];

int max(int a, int b) {
    return a > b ? a : b;
}

void new_interval_tree(int left, int right, int root, nod A[]) {
    if(left > right)
        return;

    A[root].leftBound = left;
    A[root].rightBound = right;

    if(left == right) {
        A[root].info = V[left];
    }

    if(left < right) {
        //not a leaf, continues building the tree
        int mid = (left + right) / 2;
        new_interval_tree(left, mid, root * 2, A);
        new_interval_tree(mid+1, right, root * 2 + 1, A);
        A[root].info = max(A[root * 2].info, A[root * 2 + 1].info);
    }
}

void output(nod node) {
    fout << '[' << node.leftBound << ',' << node.rightBound << "] : " << node.info << '\n';
}

int maximum_from(int a, int b, int root, nod A[]) {
    if(a <= A[root].leftBound && A[root].rightBound <= b)
        return A[root].info;
    int mij = (A[root].leftBound + A[root].rightBound) / 2;

    int max_1 = 0, max_2 = 0;
    if( a <= mij)
        max_1 = maximum_from(a, b, root * 2, A);
    if( b > mij)
        max_2 = maximum_from(a, b, root * 2 + 1, A);
    return max(max_1, max_2);
}

int BaseIntervalPosition(int a, int root, nod A[]) {
    if(A[root].leftBound == A[root].rightBound)
        return root;
    int mij = (A[root].leftBound + A[root].rightBound) / 2;
    if(a <= mij)
        return BaseIntervalPosition(a, root * 2, A);
    else
        return BaseIntervalPosition(a, root * 2 + 1, A);

}

void updateUp(int root, nod A[]) {
    if(root == 1)
        return;
    int toUpdate = root / 2;
    A[toUpdate].info = max(A[toUpdate * 2].info, A[toUpdate * 2 + 1].info);
    updateUp(toUpdate, A);
}

int main()
{
    nod A[maxN * 2];

    int N, M;
    fin >> N >> M;

    int twoToTheK = 1;
    while(twoToTheK < 2 * N - 1)
        twoToTheK <<= 1;

    for(int i=1; i<=N; i++)
        fin >> V[i];

    new_interval_tree(1, N, 1, A);

    for(; M; M--) {
        int c, a, b;
        fin >> c >> a >> b;
        if(c) {
            int root = BaseIntervalPosition(a, 1, A);
            A[root].info = b;
            updateUp(root, A);
        }
        else
            fout << maximum_from(a,b,1,A) << '\n';
    }

    for(int i = 1; i <= twoToTheK; i++)
        if(A[i].info != undefined.info)
            output(A[i]);

	fin.close();
	fout.close();
	return 0;
}