a699簡單同步模擬與候選排除

CPE:I Can Guess the Data Structure! (UVa 11995)

讓三種結構各自驗證操作紀錄,最後計算仍可能的種類。

前往題目練習 →回報教學錯誤n次操作時間 O(n log n),空間 O(n)。

解題思路

建立stack、queue與最大優先佇列,開始三者都可能。每次放入x,就把x放進所有仍可能的結構。每次取出紀錄x,分別檢查候選是否為空、其應取出的值是否等於x;不合就永久排除,符合才執行取出。

因為每個結構的取出規則固定,同一串操作對它的模擬結果是唯一的,遇到一次矛盾就不可能由後續操作補救。全部讀完,候選0個印impossible,1個印名稱,2或3個印not sure。Python以負值最小堆模擬最大優先佇列,避免誤取最小值。每組獨立初始化,讀到EOF。

Step-by-step animation

示意:放2、放1、取1、取2

回報動畫錯誤
步驟 1 / 3

放入

stack頂1、queue首2、最大堆頂2。

stack:1
queue:2
priority:2
候選數
3

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <stack>
#include <queue>
#include <string>
using namespace std;
int main() {
    int n;
    while (cin >> n) {
        stack<int> s;
        queue<int> q;
        priority_queue<int> p;
        bool a = true, b = true, c = true;
        while (n--) {
            int op, x;
            cin >> op >> x;
            if (op == 1) {
                if (a)
                    s.push(x);
                if (b)
                    q.push(x);
                if (c)
                    p.push(x);
            } else {
                if (a) {
                    if (s.empty() || s.top() != x)
                        a = false;
                    else
                        s.pop();
                }
                if (b) {
                    if (q.empty() || q.front() != x)
                        b = false;
                    else
                        q.pop();
                }
                if (c) {
                    if (p.empty() || p.top() != x)
                        c = false;
                    else
                        p.pop();
                }
            }
        }
        int count = a + b + c;
        cout << (count == 0  ? "impossible"
                 : count > 1 ? "not sure"
                 : a         ? "stack"
                 : b         ? "queue"
                             : "priority queue")
             << '\n';
    }
}

先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。

更多