B - Card Pile Editorial by en_translator
This problem relates to the data structure called stack.
A stack is data structure where elements are “stacked” in the LIFO (Last-In First-Out) manner. The elements are inserted and removed by the following two elementary operations:
- Push
- Adds a new element to the top of the stack. The new element comes above the current topmost element.
- Pop
- Retrieves and removes the topmost element of the stack. The element that was inserted lastly is removed first, achieving the LIFO behavior.
In this problem, the type-1 query corresponds to push and type-2 to pop.
This data structure called stack is provided in many programming languages as a standard feature, so you do not have to implement it from scratch.
We will now consider how we can use it to solve the problem.
First, there is a pile of \(100\) cards, all labeled by the integer \(0\). This can be done by preparing an initially empty stack, and inserting \(0\) to it \(100\) times. Then, receive queries in order, and perform a push operation if it is type \(1\) and pop operation if it is type 2.
The following is sample code in Python and C++.
stack = []
for _ in range(100):
stack.append(0)
Q = int(input())
for _ in range(Q):
query = list(map(int, input().split()))
if query[0] == 1:
x = query[1]
stack.append(x)
else:
print(stack.pop())
#include <bits/stdc++.h>
using namespace std;
int main() {
stack<int> st;
for (int i = 0; i < 100; i++) {
st.push(0);
}
int Q;
cin >> Q;
for (int i = 0; i < Q; i++) {
int c;
cin >> c;
if (c == 1) {
int x;
cin >> x;
st.push(x);
} else {
cout << st.top() << endl;
st.pop();
}
}
return 0;
}
posted:
last update: