B - Restaurant Queue Editorial by en_translator
This problem is an exercise of a data structure called a queue.
A queue is a list-like structure with first-in, first-out rule. Simply put, when taking an element out of the queue, the element that was inserted for the first time among the remaining element is always taken out.
One can use a queue to simulate the process in this problem involving waiting line of the restaurant. Arrival of a new customer to the end of the waiting line corresponds to pushing an element into the queue, and retrieving the data associated to the frontmost person corresponds to popping an element from the queue.
In most programming languages, the standard library contains an implementation of queue (such as std::queue
in C++ or collections
in collections
library in Python), so the implementation is easy. Even if it is not, it can be implemented as, for example, a linked list.
For more details on implementation, refer to the sample code.
In many programming languages including C++, the standard library provides an array data structure that supports a removal of the first element and an insertion to the last. However, beware of the computational complexity, as the cost of removal of the front element may be proportional to the number of elements in the array in some languages.
Sample code (C++)
#include <bits/stdc++.h>
using namespace std;
int main() {
int q;
cin >> q;
queue<int> que;
for (int i = 0; i < q; ++i) {
int t;
cin >> t;
if (t == 1) {
int x;
cin >> x;
que.push(x);
} else {
cout << que.front() << endl;
que.pop();
}
}
}
Sample code (Python)
from collections import deque
q = int(input())
que = deque()
for _ in range(q):
t, *x = map(int,input().split())
if t == 1:
que.append(x[0])
else:
print(que[0])
que.popleft()
posted:
last update: