a815困難依街道排序的 Hierholzer 歐拉迴路

CPE:John’s trip (UVa 302)

從指定住家出發,輸出字典序最小的全街道往返。

前往題目練習 →回報教學錯誤E 條街道,時間 O(E log E),空間 O(E+V)。

解題思路

雙向圖存在歐拉迴路的必要條件是每個路口度數皆為偶數;題目已保證所有街道連通,因此也充分。自環在同一路口的鄰接表加入兩次,正確貢獻度數 2;平行街道以各自編號區分。起點固定為第一條輸入街道較小端點。

每個鄰接表按街道編號升序排列,用 Hierholzer 取最小尚未使用邊,無邊可走時才把進入該點的街道加入反向答案,最後反轉。無法立即完成的分支會在回溯時拼接成子迴路;這種延後定稿保留最早可行的小編號前綴,得到字典序最小路線。以邊編號標記已用,不能以端點對標記;每個城市後都有空白行。

Step-by-step animation

示意:三角形街道 1:(1,2)、2:(2,3)、3:(3,1)

回報動畫錯誤
步驟 1 / 3

從住家 1 出發

1 與 3 之中先選街道 1,到路口 2。

1→2 邊1
2→3 邊2
3→1 邊3
已用邊
1

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <vector>
#include <utility>
#include <algorithm>
using namespace std;
int main() {
    int x, y, z;
    while (cin >> x >> y && (x || y)) {
        int start = min(x, y), count = 0;
        vector<vector<pair<int, int>>> adj(45);
        do {
            cin >> z;
            adj[x].push_back({z, y});
            adj[y].push_back({z, x});
            ++count;
            cin >> x >> y;
        } while (x || y);
        bool ok = true;
        for (auto &a : adj) {
            if (a.size() % 2)
                ok = false;
            sort(a.begin(), a.end());
        }
        vector<bool> used(2000);
        vector<int> next(45), answer;
        vector<pair<int, int>> stack{{start, -1}};
        if (ok)
            while (!stack.empty()) {
                int u = stack.back().first;
                while (next[u] < int(adj[u].size()) && used[adj[u][next[u]].first])
                    ++next[u];
                if (next[u] == int(adj[u].size())) {
                    int edge = stack.back().second;
                    stack.pop_back();
                    if (edge != -1)
                        answer.push_back(edge);
                } else {
                    auto [edge, v] = adj[u][next[u]++];
                    used[edge] = true;
                    stack.push_back({v, edge});
                }
            }
        if (!ok || int(answer.size()) != count)
            cout << "Round trip does not exist.\n\n";
        else {
            reverse(answer.begin(), answer.end());
            for (int i = 0; i < count; ++i)
                cout << (i ? " " : "") << answer[i];
            cout << "\n\n";
        }
    }
}

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

更多