C - Omelette Restaurant Editorial by en_translator
Consider managing the “day of purchase” of the eggs remaining in the restaurants in a queue.
Starting from an empty queue, we operate the queue in the morning, noon, and night, respectively, of day \(i\) as follows:
- Insert \(A_i\) copies of \(i\) to the tail of the queue.
- Remove \(B_i\) elements from the head of the queue.
- While the first element of the queue is \((i-D)\), repeat removing that element.
In the night action, note that the elements in the queue is always in ascending order, and the eggs purchased on day \((i-D-1)\) or before are already removed during the previous days, so in order to check whether the queue contains \((i-D)\), it is sufficient to check if the first element of the queue is \((i-D)\).
What we need to find is the number of elements in the queue after performing the operations above for \(i=1,2,\ldots,N\) in order.
Let us estimate the number of operations. For each test case, the queue will be inserted \((A_1+A_2+\cdots+A_N)\) elements, and the number of removed elements is also bounded by that count. Since insertion and removal on the queue can be done in \(O(1)\) time, the total time complexity is \(O(N\max(A_i))\).
By the constraints of the problem, the sum of \(N\) over an input is \(2\times 10^5\); with \(\max(A_i)\leq 10\), it is sufficient enough.
Therefore, the problem has been solved.
Alternatively, we may manage the number of remaining eggs purchased on day \(i\) in the \(i\)-th element of an array. In this case, if we try to inspect the stock for the \(D\) days, it costs \(\Theta(ND)\) time, which will exceed the execution time limit; therefore, we also need to manage on what day the oldest remaining egg was purchased.
Sample code in C++:
#include <bits/stdc++.h>
using namespace std;
int main(void){
int t;
cin>>t;
for(int itest=0;itest<t;itest++){
int n,d;
cin>>n>>d;
vector<int>a(n),b(n);
for(int i=0;i<n;i++)cin>>a[i];
for(int i=0;i<n;i++)cin>>b[i];
int x;
queue<int>q;
for(int i=0;i<n;i++){
for(int j=0;j<a[i];j++)q.push(i);
for(int j=0;j<b[i];j++)q.pop();
while((!q.empty())&&(q.front()==i-d))q.pop();
}
cout<<((int)(q.size()))<<endl;
}
return 0;
}
posted:
last update: