a923困難

95 全國資訊學科能力競賽(2006)|快遞服務

利用上一個服務地點作為已知車位。

解題思路

處理完第i個要求後,至少一輛車停在該要求地點last。只需記錄另兩車位置(a,b),車輛無個別差異,可把a、b排序作為狀態。初始last=1,另兩車在2、3。

下一要求為v時,有三種選擇:last車移動,閒車仍是(a,b);a車移動,閒車變成(last,b);b車移動,閒車變成(last,a)。加上相應有向D費用後取最小。枚舉全部可能服務車,依序保留所有必要資訊,故不漏最優分派。

Q個要求、m個地點,時間O(Qm²),空間O(m²)。 Python read().split() 另需 O(I) 輸入文字與詞元暫存,I 為總輸入大小。

Step-by-step animation

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

回報動畫錯誤
步驟 1 / 3

示意首個要求4

四地點間不同點距離均1。

車:1,2,3
需求
4

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
int main() {
    int m;
    cin >> m;
    vector<vector<long long>> D(m, vector<long long>(m));
    for (auto &r : D)
        for (auto &x : r)
            cin >> x;
    int last = 0, v;
    map<pair<int, int>, long long> d;
    d[{1, 2}] = 0;
    while (cin >> v) {
        --v;
        map<pair<int, int>, long long> nd;
        auto put = [&](int a, int b, long long cost) {
            if (a > b)
                swap(a, b);
            pair<int, int> key = {a, b};
            if (!nd.count(key) || cost < nd[key])
                nd[key] = cost;
        };
        for (auto [key, c] : d) {
            auto [a, b] = key;
            put(a, b, c + D[last][v]);
            put(last, b, c + D[a][v]);
            put(last, a, c + D[b][v]);
        }
        d = move(nd);
        last = v;
    }
    long long ans = LLONG_MAX;
    for (auto [key, c] : d)
        ans = min(ans, c);
    cout << ans << '\n';
}

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

更多