題目鏈接
題意:給定一個有向圖,求最少劃分成幾個部分滿足下面條件
互相可達的點必須分到一個集合
一個對點(u, v)必須至少有u可達v或者v可達u
一個點只能分到一個集合
思路:先強連通縮點,然後二分圖匹配求最小路徑覆蓋
代碼:
#include#include #include #include #include using namespace std; const int N = 5005; int t, n, m; vector g[N]; stack S; int pre[N], dfn[N], sccn, sccno[N], dfs_clock; void dfs(int u) { pre[u] = dfn[u] = ++dfs_clock; S.push(u); for (int i = 0; i < g[u].size(); i++) { int v = g[u][i]; if (!pre[v]) { dfs(v); dfn[u] = min(dfn[u], dfn[v]); } else if (!sccno[v]) dfn[u] = min(dfn[u], pre[v]); } if (dfn[u] == pre[u]) { sccn++; while (1) { int x = S.top(); S.pop(); sccno[x] = sccn; if (x == u) break; } } } void find_scc() { sccn = dfs_clock = 0; memset(pre, 0, sizeof(pre)); memset(sccno, 0, sizeof(sccno)); for (int i = 1; i <= n; i++) if (!pre[i]) dfs(i); } int left[N], vis[N]; vector scc[N]; bool match(int u) { for (int i = 0; i < scc[u].size(); i++) { int v = scc[u][i]; if (vis[v]) continue; vis[v] = 1; if (!left[v] || match(left[v])) { left[v] = u; return true; } } return false; } int hungary() { memset(left, 0, sizeof(left)); int ans = 0; for (int i = 1; i <= sccn; i++) { memset(vis, 0, sizeof(vis)); if (match(i)) ans++; } return sccn - ans; } int main() { scanf("%d", &t); while (t--) { scanf("%d%d", &n, &m); for (int i = 1; i <= n; i++) g[i].clear(); int u, v; while (m--) { scanf("%d%d", &u, &v); g[u].push_back(v); } find_scc(); for (int i = 1; i <= sccn; i++) scc[i].clear(); for (int u = 1; u <= n; u++) { for (int j = 0; j < g[u].size(); j++) { int v = g[u][j]; if (sccno[u] == sccno[v]) continue; scc[sccno[u]].push_back(sccno[v]); } } printf("%d\n", hungary()); } return 0; }