Cod sursa(job #3319825)

Utilizator raul41917raul rotar raul41917 Data 3 noiembrie 2025 12:38:52
Problema Arbori de intervale Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.58 kb
#include <fstream>
#include <iostream>
#include <map>

using namespace std;

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

struct interval{
    int left, right, max;
};

map<int, int> positionsMap;
int counter = 0;

int buildTree(interval interval[], int currentIndex, int left, int right){
    interval[currentIndex].left = left;
    interval[currentIndex].right = right;

    if(left == right){
        int value;
        fin >> value;

        cout << counter << endl;
        positionsMap.insert(pair(counter++, currentIndex));
        interval[currentIndex].max = value;
        return value;
    }else{
        int middle = (left + right) / 2;
        int maxLeft = buildTree(interval, currentIndex * 2 + 1, left, middle);
        int maxRight = buildTree(interval, currentIndex * 2 + 2, middle + 1, right);
        interval[currentIndex].max = max(maxLeft, maxRight);
        return interval[currentIndex].max;
    }

}

int lookupForMaximum(int n, interval intervalArray[], int currentIndex, int leftIndexQuery, int rightIndexQuery, int left, int right){
    if(left < 0 || right > n)
        return -1;
    if(leftIndexQuery > right)
        return -1;
    if(rightIndexQuery < left)
        return -1;
    if(leftIndexQuery <= left && rightIndexQuery >= right){
        return intervalArray[currentIndex].max;
    }
    return max(lookupForMaximum(n, intervalArray, currentIndex * 2 + 1, leftIndexQuery, rightIndexQuery, left, (left + right) / 2),
               lookupForMaximum(n, intervalArray, currentIndex * 2 + 2, leftIndexQuery, rightIndexQuery, (left + right) / 2 + 1, right));

}

int main() {

    int n, m;
    fin >> n >> m;

    interval intervalVector[300000];
    buildTree(intervalVector, 0, 0, n - 1);

    for(pair<int, int> p: positionsMap)
        cout <<  p.first << " " << p.second << endl;

    for(int i = 0; i < m; i++){
        int op, a, b;
        fin >> op >> a >> b;
        a--;
        b--;
        if(op == 0){
            fout << lookupForMaximum(n-1,intervalVector, 0,  a, b, 0, n - 1) << "\n";
        }else{
            b++;
            int posA = positionsMap.at(a);
            intervalVector[posA].max = b;
            int parentIndex = (posA - 1) / 2;

            while(true){
                int leftChildMax = intervalVector[parentIndex * 2 + 1].max;
                int rightChildMax = intervalVector[parentIndex * 2 + 2].max;
                intervalVector[parentIndex].max = max(leftChildMax, rightChildMax);
                if(parentIndex == 0)
                    break;
                parentIndex = (parentIndex - 1) / 2;
            }
        }
    }
    return 0;
}