Cod sursa(job #2659181)

Utilizator bori2000Fazakas Borbala bori2000 Data 16 octombrie 2020 00:32:03
Problema Arbori de intervale Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.86 kb
#include <fstream>

using namespace std;

class Tree {
 public:
  int leftIndex, rightIndex;
  int maxValue;
  Tree* leftTree, *rightTree;

  Tree(int leftIndex, int rightIndex) {
    this->leftIndex = leftIndex;
    this->rightIndex = rightIndex;
    if (leftIndex != rightIndex) {
      int middle = (leftIndex + rightIndex) / 2;
      leftTree = new Tree(leftIndex, middle);
      rightTree = new Tree(middle + 1, rightIndex);
    }
  }

  int getMaxValue(int intervalLeftIndex, int intervalRightIndex) {
    if (intervalLeftIndex == leftIndex && intervalRightIndex == rightIndex) {
      return this->maxValue;
    } else {
      int middle = (leftIndex + rightIndex) / 2;
      int leftMax = 0, rightMax = 0;
      if (intervalLeftIndex <= middle) {
        leftMax = leftTree -> getMaxValue(intervalLeftIndex, min(middle, intervalRightIndex));
      }
      if (intervalRightIndex > middle) {
        rightMax = rightTree -> getMaxValue(max(middle + 1, intervalLeftIndex), intervalRightIndex);
      }
      return max(leftMax, rightMax);
    }
  }

  void update(int index, int value) {
    if (leftIndex == rightIndex) {
      this -> maxValue = value;
    } else {
      int middle = (leftIndex + rightIndex) / 2;
      if (index <= middle) {
        leftTree -> update(index, value);
      }
      if (index > middle) {
        rightTree -> update(index, value);
      }
      this->maxValue = max(leftTree -> maxValue, rightTree -> maxValue);
    }
  }
};

int main() {
  ifstream f("arbint.in");
  ofstream g("arbint.out");
  int n, m;
  f >> n >> m;
  int a[n+1];
  Tree* root = new Tree(1, n);
  for (int i = 0; i < n; i++) {
    f >> a[i];
    root -> update(i + 1, a[i]);
  }
  int command, x, y;
  for (int i = 0; i < m; i++) {
    f >> command >> x >> y;
    if (command == 0) {
      g << root -> getMaxValue(x, y) << endl;
    } else {
      root -> update(x, y);
    }
  }
  return 0;
}