2
int occ = -1; // No row occupied initially3
vector<long long> sumTree, maxTree;4
int treeSize = 0, rowSeats = 0;7
BookMyShow(int n, int m) {9
this->treeSize = (int)2 * pow(2, ceil((double)log2(n)));10
sumTree.resize(treeSize);11
maxTree.resize(treeSize);18
void constructSumTree(int m) {19
int n = this->treeSize / 2;22
for (int i = n; i < 2 * n; i++) this->sumTree[i] = (long long)m;24
// Forming the higher nodes25
for (int i = n - 1; i >= 1; i--)26
this->sumTree[i] = this->sumTree[2 * i] + this->sumTree[2 * i + 1];29
void constructMaxTree(int m) {30
int n = this->treeSize / 2;33
for (int i = n; i < 2 * n; i++) this->maxTree[i] = (long long)m;35
// Forming the higher nodes36
for (int i = n - 1; i >= 1; i--)37
this->maxTree[i] = max(this->maxTree[2 * i], this->maxTree[2 * i + 1]);40
long long rangeSum(int minRow, int maxRow) {45
while (minRow <= maxRow) {46
if (minRow % 2 == 1) sum += this->sumTree[minRow++]; // Right child47
if (maxRow % 2 == 0) sum += this->sumTree[maxRow--]; // Left child55
void updateSumTree(int index, int newValue) {56
int n = this->treeSize / 2;59
this->sumTree[index] = newValue; // Update leaf62
this->sumTree[index] = this->sumTree[2 * index] + this->sumTree[2 * index + 1];67
long long rangeMax(int minRow, int maxRow) {69
int n = this->treeSize / 2;72
while (minRow <= maxRow) {73
if (minRow % 2 == 1) ans = max(ans, this->maxTree[minRow++]); // Right child74
if (maxRow % 2 == 0) ans = max(ans, this->maxTree[maxRow--]); // Left child79
// cout<<"range max over"<<'\n';83
void updateMaxTree(int index, int newValue) {84
int n = this->treeSize / 2;87
this->maxTree[index] = newValue; // Update leaf90
this->maxTree[index] = max(this->maxTree[2 * index], this->maxTree[2 * index + 1]);95
vector<int> gather(int k, int maxRow) {97
if (maxRow < minRow) return {};98
if (rangeMax(minRow, maxRow) < k) return {};100
int minIndex = maxRow;102
int low = minRow, high = maxRow;103
while (low <= high) {104
int midRow = (low + high) / 2;105
int maxSeats = rangeMax(minRow, midRow);114
int r = minIndex, c = this->rowSeats - seats;116
// Updatng the segment trees117
this->updateMaxTree(minIndex, seats - k);118
this->updateSumTree(minIndex, seats - k);122
bool scatter(int k, int maxRow) {123
int minRow = occ + 1;124
if (maxRow < minRow) return false;125
if (rangeSum(minRow, maxRow) < k) return false;127
int minIndex = maxRow;129
int low = minRow, high = maxRow;130
while (low <= high) {131
int midRow = (low + high) / 2;132
long long rangeSeats = rangeSum(minRow, midRow);133
if (rangeSeats >= k) {141
// Updating the occupied rows144
// Updating the segment trees145
this->updateSumTree(minIndex, seats - k);146
this->updateMaxTree(minIndex, seats - k);152
* Your BookMyShow object will be instantiated and called as such:153
* BookMyShow* obj = new BookMyShow(n, m);154
* vector<int> param_1 = obj->gather(k,maxRow);155
* bool param_2 = obj->scatter(k,maxRow);