题意
题解
求二分图最大匹配的可行边。
若 ( x , y ) (x,y) (x,y) 至少属于一个最大匹配的方案,则称 ( x , y ) (x,y) (x,y) 为二分图最大匹配的可行边。
题中的二分图 G G G 构成一组完备匹配。若 ( x , y ) (x,y) (x,y) 为可行边,当且仅当满足下述两个条件之一: ( x , y ) (x,y) (x,y) 当前是匹配边; ( x , y ) (x,y) (x,y) 是非匹配边,设当前 x x x 与 v v v 匹配, y y y 与 u u u 匹配,将 ( x , y ) (x,y) (x,y) 设置为匹配边后,节点 u , v u,v u,v 失去匹配,此时必须能找到一条从 u u u 到 v v v 的增广路。
考虑使用网络流求解二分图最大匹配的残余网络中删去源点、汇点的部分 G ′ G' G′,则非匹配为左部点向右部点的有向边,匹配边为右部点向左部点的有向边。若满足上述条件,即找到一条从 u u u 到 v v v 的增广路,则 u → v , v → x , x → y , y → u u\rightarrow v,v\rightarrow x,x\rightarrow y,y\rightarrow u u→v,v→x,x→y,y→u 构成一个环。那么构造按照残余网络结构建图, T a r j a n Tarjan Tarjan 求解 S C C SCC SCC。此时可行边的判定条件改写为: ( x , y ) (x,y) (x,y) 当前是二分图 G G G 的匹配边,或者 x , y x,y x,y 在 G ′ G' G′ 中属于同一个 S C C SCC SCC。
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <vector>
using namespace std;
typedef vector<int> vec;
const int maxn = 2005, maxv = maxn * 2, maxe = 200005;
int N, match[maxn];
vec chs[maxn], res[maxn];
int tot, head[maxv], to[maxe], nxt[maxe];
int num, dfn[maxv], low[maxv];
int scc, sc[maxv], top, st[maxv];
bool ins[maxv];
inline void add(int x, int y) { to[++tot] = y, nxt[tot] = head[x], head[x] = tot; }
void tarjan(int x)
{
low[x] = dfn[x] = ++num;
st[++top] = x, ins[x] = 1;
for (int i = head[x]; i; i = nxt[i])
{
int y = to[i];
if (!dfn[y])
tarjan(y), low[x] = min(low[x], low[y]);
else if (ins[y])
low[x] = min(low[x], dfn[y]);
}
if (low[x] == dfn[x])
{
++scc;
int y;
do
{
y = st[top--], ins[y] = 0, sc[y] = scc;
} while (y != x);
}
}
int main()
{
scanf("%d", &N);
for (int i = 1, k; i <= N; ++i)
{
scanf("%d", &k);
chs[i] = vec(k);
for (int j = 0; j < k; ++j)
scanf("%d", &chs[i][j]);
}
for (int i = 1; i <= N; ++i)
scanf("%d", match + i);
for (int x = 1; x <= N; ++x)
for (int i = 0; i < (int)chs[x].size(); ++i)
{
int y = chs[x][i];
if (match[x] != y)
add(x, N + y);
}
for (int i = 1; i <= N; ++i)
add(N + match[i], i);
int lim = 2 * N;
for (int i = 1; i <= lim; ++i)
if (!dfn[i])
tarjan(i);
for (int x = 1; x <= N; ++x)
{
res[x].push_back(match[x]);
for (int i = head[x]; i; i = nxt[i])
{
int y = to[i];
if (sc[x] == sc[y])
res[x].push_back(y - N);
}
}
for (int i = 1; i <= N; ++i)
{
printf("%d", (int)res[i].size());
sort(res[i].begin(), res[i].end());
for (int j = 0; j < (int)res[i].size(); ++j)
printf(" %d", res[i][j]);
putchar('\n');
}
return 0;
}