b059中等

108 臺北市資訊學科能力競賽(2019)|打卡遊戲(Checkin)

將任務圖分解成最少條不重複邊的行程。

解題思路

每項任務是一條無向邊,兩次任務能不換車接續,等價於它們在一條邊不重複的行程中相連。所有公里費固定,起跳費為正,所以只需最少行程數。

對每個含邊連通分量,若有o個奇度點,至少要o/2條行程,因每條最多提供兩個奇端點。若o=0,仍需一條歐拉迴路。

把奇度點兩兩補邊可形成歐拉迴路,移除補邊即得o/2條行程,達到下界。答案為各分量max(1,o/2)之和,距離及費率不影響車輛數。

時間 O(A+B+K),空間 O(A+B)。

Step-by-step animation

奇度點與最少邊跡覆蓋|三個任務1–2、2–3、2–4是一個分量。

回報動畫錯誤
步驟 1 / 3

建圖

三個任務1–2、2–3、2–4是一個分量。

度1
度3
度1
度1
奇度點
4

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
int main() {
    int a, b, k;
    long long s, m;
    cin >> a >> b >> s >> m >> k;
    int n = a + b;
    vector<int> p(n), d(n), odd(n), used(n);
    iota(p.begin(), p.end(), 0);
    function<int(int)> f = [&](int x) { return p[x] == x ? x : p[x] = f(p[x]); };
    while (k--) {
        int u, v;
        long long w;
        cin >> u >> v >> w;
        --u;
        v = a + v - 1;
        d[u]++;
        d[v]++;
        int x = f(u), y = f(v);
        if (x != y)
            p[x] = y;
    }
    for (int i = 0; i < n; i++)
        if (d[i]) {
            int r = f(i);
            used[r] = 1;
            odd[r] += d[i] % 2;
        }
    int ans = 0;
    for (int i = 0; i < n; i++)
        if (used[i])
            ans += max(1, odd[i] / 2);
    cout << ans << "\n";
}

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

更多