C - Tallest at the Moment Editorial by en_translator Editorial for printing
This problem can be solved in several ways. Here, we introduce a fast solution that maintains “Takahashi’s that may become tallest.”
For two Takahashi’s, if one is taller and will stay longer than the other, the answer is not affected if the latter Takahashi is not in the meeting room at all.
By kicking out all such Takahashi’s from the meeting room, one can assume that \(H _ 1\ge H _ 2\ge\cdots\ge H _ N\) and \(L _ 1\le L _ 2\le\cdots\le L _ N\).
Then the problem can be solved by binary search.
Removing irrelevant Takahashi from the meeting room can be done in a total of \(O(N)\) time using a stack.
The total time complexity is \(O(N+Q\log N)\).
The following is sample code.
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
using namespace std;
unsigned N;
cin >> N;
vector<pair<unsigned, unsigned>> takahashi;
for (unsigned i = 0; i < N; ++i) {
unsigned H, L;
cin >> H >> L;
while (!empty(takahashi) && takahashi.back().first <= H) // If there is shorter Takahashi leaving earlier
takahashi.pop_back(); // let him leave the room in the first place
takahashi.emplace_back(H, L);
}
unsigned Q;
cin >> Q;
for (unsigned i = 0; i < Q; ++i) {
unsigned T;
cin >> T;
// binary search by the second element of the pairs to find the tallest Takahashi leaving later than T minutes from now
cout << ranges::upper_bound(takahashi, T, {}, &pair<unsigned, unsigned>::second)->first << endl;
}
return 0;
}
posted:
last update: