a828中等路徑鍵值、父節點完整性與層序排序

CPE:Trees on the level (UVa 122)

檢查重複指定與缺祖先,再輸出完整二元樹。

前往題目練習 →回報教學錯誤每棵樹 V 個節點、最長路徑 H、值最多 L 位;時間 O(VL+V(H+1) log(V+1)),狀態空間 O(V(L+H+1))。Python 整批讀入另需 O(總輸入長) 空間。

解題思路

把每個路徑字串作為唯一鍵,值是節點內容。重複鍵即使數值相同也代表重複指定,必須保留失敗旗標。當遇到 () 時檢查根的空路徑存在,且每個非根路徑去掉最後一字元後的父路徑也存在。逐點的父節點檢查自然保證整條祖先鏈完整。

完整時依『路徑長度、路徑字典序』排序:長度就是深度,而相同深度下 L<R 對應由左到右,所以這正是層序。否則只輸出 not complete。() 代表目前樹結束而不是整份輸入結束;印完後清空字典與重複旗標,繼續讀到 EOF。

節點值沒有位數上限,而且只需保存與輸出,不必做算術。兩種語言都將值存成十進位字串:去掉可選的正負號後先移除前導零,全零統一成 0,非零負數才保留負號。題目保證值為正,因此合法資料輸出不含正號或多餘前導零;不使用 stoi 或 int() 解析長數值,也不更改 Python 的十進位轉換安全設定。

Step-by-step animation

示意:(4,L)、(8,R)、(5,) 依此順序輸入

回報動畫錯誤
步驟 1 / 3

讀 L

記錄路徑 L 的值 4,根尚未出現,先不提早判錯。

L:4
節點數
1

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <string>
#include <map>
#include <vector>
#include <algorithm>
using namespace std;
string normalizeDecimal(const string &s) {
    size_t first = 0;
    bool negative = false;
    if (!s.empty() && (s[0] == '+' || s[0] == '-')) {
        negative = s[0] == '-';
        first = 1;
    }
    while (first < s.size() && s[first] == '0')
        ++first;
    if (first == s.size())
        return "0";
    string digits = s.substr(first);
    return negative ? "-" + digits : digits;
}
int main() {
    map<string, string> tree;
    bool duplicate = false;
    string token;
    while (cin >> token) {
        if (token != "()") {
            size_t comma = token.find(',');
            string value = normalizeDecimal(token.substr(1, comma - 1));
            string path = token.substr(comma + 1, token.size() - comma - 2);
            if (tree.count(path))
                duplicate = true;
            tree[path] = value;
            continue;
        }
        bool ok = !duplicate && tree.count("");
        vector<string> paths;
        for (const auto &[path, value] : tree) {
            if (!path.empty() && !tree.count(path.substr(0, path.size() - 1)))
                ok = false;
            paths.push_back(path);
        }
        if (!ok)
            cout << "not complete\n";
        else {
            sort(paths.begin(), paths.end(), [](const string &a, const string &b) {
                return a.size() != b.size() ? a.size() < b.size() : a < b;
            });
            for (int i = 0; i < int(paths.size()); ++i)
                cout << (i ? " " : "") << tree[paths[i]];
            cout << '\n';
        }
        tree.clear();
        duplicate = false;
    }
}

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

更多