a898中等

96 全國資訊學科能力競賽(2007)|合法執行路徑問題

逐條驗證相鄰節點與返回位置。

解題思路

依題目固定流程建立非呼叫節點的合法下一步。遇到 11、5、6 呼叫時,下一步必須是 1,並將呼叫行號+1 推入堆疊。

遇到返回點 8,必須有尚未返回的呼叫,下一節點也必須等於堆疊頂,然後彈出。路徑須從 9 開始、在 12 結束且堆疊為空。堆疊正好記錄遞迴嵌套,因此不能跳過尚未完成的呼叫。

每條長度 L 的路徑時間 O(L),空間 O(L)。

Step-by-step animation

教學示意(以步驟描述中的輸入為準)

回報動畫錯誤
步驟 1 / 3

主程式呼叫

9→10→11→1,將12推入堆疊。

9
10
11
1
堆疊
12

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
int main() {
    string line;
    map<int, vector<int>> e = {{9, {10}}, {10, {11}}, {1, {2}}, {2, {3, 4}},
                               {3, {7}},  {4, {5}},   {7, {8}}};
    while (getline(cin, line)) {
        istringstream in(line);
        vector<int> a;
        int x;
        while (in >> x)
            a.push_back(x);
        if (a == vector<int>{0})
            break;
        bool ok = a.size() > 1 && a.front() == 9 && a.back() == 12;
        vector<int> st;
        for (int i = 0; ok && i + 1 < (int)a.size(); i++) {
            int x = a[i], y = a[i + 1];
            if (x == 11 || x == 5 || x == 6) {
                if (y != 1)
                    ok = false;
                else
                    st.push_back(x + 1);
            } else if (x == 8) {
                if (st.empty() || st.back() != y)
                    ok = false;
                else
                    st.pop_back();
            } else {
                auto v = e[x];
                if (find(v.begin(), v.end(), y) == v.end())
                    ok = false;
            }
        }
        cout << (ok && st.empty() ? "valid" : "invalid") << '\n';
    }
}

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

更多