Hướng giải của Queue bang hai Stack


Nhớ rằng hướng dẫn giải này chỉ nên sử dụng khi bế tắc, và tuyệt đối không nên sao chép mã nguồn kèm theo. Hãy tôn trọng tác giả bài tập và người viết hướng dẫn giải.
Nộp mã nguồn lời giải chính thức trước khi giải bài tập đó có thể khiến bạn bị ban.

Thuật toán

Dùng hai stack: s1 để enqueue, s2 để dequeue.

  • Khi enqueue: push vào s1
  • Khi dequeue/front: nếu s2 rỗng, chuyển toàn bộ phần tử từ s1 sang s2 (lật ngược thứ tự)
  • Lấy/top phần tử từ s2

Độ phức tạp: O(1) trả góp (amortized O(1)) cho mỗi thao tác.

Code mẫu

#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int N;
    cin >> N;
    stack<int> s1, s2;

    while (N--) {
        int t;
        cin >> t;
        if (t == 1) {
            int x;
            cin >> x;
            s1.push(x);
        } else if (t == 2 || t == 3) {
            if (s2.empty()) {
                while (!s1.empty()) {
                    s2.push(s1.top());
                    s1.pop();
                }
            }
            if (t == 2) {
                if (s2.empty()) cout << "-1\n";
                else {
                    cout << s2.top() << "\n";
                    s2.pop();
                }
            } else {
                if (s2.empty()) cout << "-1\n";
                else cout << s2.top() << "\n";
            }
        }
    }
    return 0;
}
s1, s2 = [], []
n = int(input())
for _ in range(n):
    parts = input().split()
    if parts[0] == '1':
        s1.append(int(parts[1]))
    elif parts[0] == '2':
        if not s2:
            while s1:
                s2.append(s1.pop())
        print(s2.pop() if s2 else -1)
    elif parts[0] == '3':
        if not s2:
            while s1:
                s2.append(s1.pop())
        print(s2[-1] if s2 else -1)

Nhận xét

Không có ý kiến tại thời điểm này.