a530中等每個起點 BFS 比較有向距離

CPE:Edgetown’s Traffic Jams (UVa 12319)

完整檢查所有有順序的路口對及不可達情形。

前往題目練習 →回報教學錯誤時間 O(n(n+m₁+m₂)),空間 O(n+m₁+m₂)。

解題思路

每行鄰接列表只建立從第一個編號指向後續編號的有向邊,不可自行補成雙向。所有邊長為 1,因此分別對原路網與新路網,從每一個起點做 BFS 得到最短路徑。

對每個有順序的點對 (s,v),先確認新距離不是不可達,再檢查 new≤A×old+B。任何一對不符合就輸出 No,全部符合才是 Yes。鄰接表每行長度不固定,必須整行讀取;n=0 結束。BFS 比 Floyd 更直接利用道路皆為單位權重的特性。

Step-by-step animation

示意:原本三點兩兩相通,新圖 1→2→3→1,A=1、B=0

回報動畫錯誤
步驟 1 / 3

原距離

從 1 到另外兩點都只需一條邊。

d(1,1)=0
d(1,2)=1
d(1,3)=1
上限 1→3
1

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>
#include <numeric>
#include <cmath>
#include <iomanip>
#include <queue>
#include <deque>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <array>
#include <tuple>
#include <functional>
#include <limits>
#include <cstdint>
#include <cctype>
#include <utility>
using namespace std;

vector<int> bfs(const vector<vector<int>> &g, int s) {
    vector<int> d(g.size(), -1);
    queue<int> q;
    d[s] = 0;
    q.push(s);
    while (!q.empty()) {
        int u = q.front();
        q.pop();
        for (int v : g[u])
            if (d[v] < 0) {
                d[v] = d[u] + 1;
                q.push(v);
            }
    }
    return d;
}
int main() {
    int n;
    string line;
    while (cin >> n && n) {
        getline(cin, line);
        vector<vector<int>> old(n), fresh(n);
        for (auto *graph : {&old, &fresh})
            for (int row = 0; row < n; ++row) {
                getline(cin, line);
                istringstream in(line);
                int u, v;
                in >> u;
                while (in >> v)
                    (*graph)[u - 1].push_back(v - 1);
            }
        int a, b;
        cin >> a >> b;
        bool ok = true;
        for (int s = 0; s < n && ok; ++s) {
            auto x = bfs(old, s), y = bfs(fresh, s);
            for (int v = 0; v < n; ++v)
                if (y[v] < 0 || y[v] > a * x[v] + b)
                    ok = false;
        }
        cout << (ok ? "Yes" : "No") << '\n';
    }
}

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

更多