跳到正文

题解

在八角柜台

Loop1st约 4 分钟
原文
文章信息与版本

文章信息

发布
2025年12月11日
收录
2025年12月12日
更新
2026年8月26日
篇幅
约 4 分钟
获赞
2
题目
P2764

版本

  1. v2当前
  2. v1

有意思的典题。

二分图做法咋都似了。

首先考虑拆点,将 uu 拆成两个点 uu 和 u+nu + n,u→vu \rightarrow v 连边则令 uu 连边 v+nv + n,这样就变成了二分图,而 DAG 最小链覆盖是等于 nn 减其对应二分图的最大匹配,证明请见OI-Wiki。

那么我们之间跑一遍匈牙利即可。

输出答案咋办呢,我们只需要当左边的 uu 匹配右边的 vv 时多记一个 fu=vf_u = v,即双向地记下 这个匹配。每次找到链尾,因为链尾的 ff 为 00。然后不断找其前面的点即可。

C++
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
// typedef __int128 i128;
typedef pair<int, int> pii;
const int N = 3e2 + 10, mod = 998244353;
template<typename T>
void dbg(const T &t) { cout << t << endl; }
template<typename Type, typename... Types>
void dbg(const Type& arg, const Types&... args) {
    cout << arg << ' ';
    dbg(args...);
}
namespace Loop1st {
int n, m, b[N], f[N];
vector<int>e[N];
bool dfs(int u) {
    for (int v : e[u]) if (!b[v]) {
        b[v] = 1;
        if (!f[v] || dfs(f[v])) {
            f[v] = u;
            f[u] = v;
            return 1;
        }
    }
    return 0;
}
void print(int u) {
    u += n;
    do {
        u -= n;
        cout << u << ' ';
        b[u] = 1;
        u = f[u];
    } while (u);
    cout << '\n';
}
void main() {
    cin >> n >> m;
    for (int i = 1, u, v; i <= m; i++) {
        cin >> u >> v;
        e[u].push_back(v + n);
    }
    int ans = 0;
    for (int i = 1; i <= n; i++) {
        for (int j = n + 1; j <= n + n; j++) b[j] = 0;
        if (dfs(i)) ans++;
    }
    memset(b, 0, sizeof b);
    for (int i = 1; i <= n; i++) if (!f[i]) {
        int u = i;
        vector<int>c;
        while (true) {
            c.push_back(u);
            bool fl = 0;
            for (int x = 1; x <= n && !fl; x++) if (f[x] - n == u) fl = 1, u = x;
            if (!fl) break;
        }
        reverse(c.begin(), c.end());
        for (int x : c) cout << x << ' ';
        cout << '\n';
    }
    cout << n - ans << '\n';
}

}
int main() {
    // freopen("data.in", "r", stdin);
    // freopen("data.out", "w", stdout);
    ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
    Loop1st::main();
    return 0;
}
原文