a274困難二分圖最大獨立集・分層增廣匹配

TOI 2022/04 潛力組:防守城堡

用最大匹配求出最多互不衝突的列、欄砲台。

前往題目練習 →回報教學錯誤時間 O((T+M+N)√(M+N))、空間 O(T+M+N)。M、N ≤ 500,T ≤ 250000;分層搜尋深度最多 500,Python 明確設定足夠遞迴上限。

解題思路

左側放 M 個列砲台、右側放 N 個欄砲台,每個陷阱連成一條衝突邊。合法砲台集合不能同時選邊的兩端,正是二分圖獨立集。其補集必須覆蓋每條邊,因此最大獨立集大小等於 M+N 減最小頂點覆蓋。

Kőnig 定理指出二分圖最小頂點覆蓋大小等於最大匹配。Hopcroft–Karp 先從所有未匹配列做 BFS,找出最短增廣路的分層;再用 DFS 只沿層數增加的邊,同一輪盡量加入多條最短增廣路。匹配邊反轉後,匹配數每條增加 1。若 BFS 再也碰不到未匹配欄,就沒有增廣路,匹配已最大,輸出 M+N−matching。每輪的鄰邊游標避免重複掃描失敗分支。

Step-by-step animation

範例陷阱 (0,0)、(0,1)、(1,1)、(2,1)

回報動畫錯誤
步驟 1 / 3

匹配列 0

將列 0 配給欄 0,得到第一條匹配邊。

列0↔欄0
欄1空
列1空
列2空
matching
1

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <vector>
#include <functional>
#include <queue>
#include <algorithm>
using namespace std;
int main() {
    int m, n, t;
    cin >> m >> n >> t;
    vector<vector<int>> g(m);
    for (int i = 0, r, c; i < t; ++i) {
        cin >> r >> c;
        g[r].push_back(c);
    }
    vector<int> left(m, -1), right(n, -1), distance(m), cursor(m);
    int shortest = 0, matching = 0;
    auto layers = [&]() {
        queue<int> q;
        fill(distance.begin(), distance.end(), -1);
        for (int r = 0; r < m; ++r)
            if (left[r] < 0) {
                distance[r] = 0;
                q.push(r);
            }
        shortest = m + 1;
        while (!q.empty()) {
            int r = q.front();
            q.pop();
            if (distance[r] >= shortest)
                continue;
            for (int c : g[r]) {
                int next = right[c];
                if (next < 0)
                    shortest = distance[r] + 1;
                else if (distance[next] < 0) {
                    distance[next] = distance[r] + 1;
                    q.push(next);
                }
            }
        }
        return shortest <= m;
    };
    function<bool(int)> augment = [&](int r) {
        while (cursor[r] < int(g[r].size())) {
            int c = g[r][cursor[r]++], next = right[c];
            if ((next < 0 && distance[r] + 1 == shortest) ||
                (next >= 0 && distance[next] == distance[r] + 1 && augment(next))) {
                left[r] = c;
                right[c] = r;
                return true;
            }
        }
        distance[r] = -1;
        return false;
    };
    while (layers()) {
        fill(cursor.begin(), cursor.end(), 0);
        for (int r = 0; r < m; ++r)
            if (left[r] < 0 && augment(r))
                ++matching;
    }
    cout << m + n - matching << '\n';
}

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

更多