题目链接
https://ac.nowcoder.com/acm/problem/51319
题意
求每个男孩可以选择多少个女孩使得完美匹配依然存在。
思路
建图时, 男孩对喜欢的女孩建一条单向边, 和暂时匹配的女孩建一条双向边, 当男孩和女孩同处于一个强连通分量并且图中有边, 男孩就可以选择这个女孩。
AC代码
#include<bits/stdc++.h>
using namespace std;
const int maxn = 5000;
const int INF = 0x3f3f3f3f;
struct node{
int to, next;
} edge[maxn * 100];
int tot, sc, cnt;
int dfn[maxn], low[maxn];
int top, stack1[maxn * 100];
int scc[maxn];
int head[maxn], vis[maxn];
int sz[maxn];
void add(int from, int to){
edge[++cnt].to = to;edge[cnt].next = head[from];head[from] = cnt;
}
void ins(int u, int v){add(u, v); add(v, u);}
void Tarjan(int u){
dfn[u] = low[u] = ++tot;
vis[u] = 1;
stack1[top++] = u;
for(int i = head[u];i != -1;i = edge[i].next){
int v = edge[i].to;
if(!dfn[v]){
Tarjan(v);
low[u] = min(low[u], low[v]);
}
else if(vis[v]) low[u] = min(low[u], dfn[v]);
}
if(dfn[u] == low[u]){
sc++;
int v;
do{
v = stack1[--top];
scc[v] = sc;
vis[v] = 0;
sz[sc]++;
}while(v != u);
}
}
void init(){
tot = cnt = sc = 0;
memset(head, -1, sizeof(head));
memset(dfn, 0, sizeof(dfn));
memset(low, 0, sizeof(low));
memset(scc, 0, sizeof(scc));
}
int main()
{
std::ios::sync_with_stdio(false);
int n;
while(cin >> n){
init();
for(int i = 1;i <= n;i++){
int m;
cin >> m;
for(int j = 0;j < m;j++){
int x;
cin >> x;
add(i, x + n);
}
}
for(int i = 1;i <= n;i++){
int x;
cin >> x;
ins(i, x + n);
}
for(int i = 1;i <= 2 * n;i++) if(!dfn[i]) Tarjan(i);
for(int i = 1;i <= n;i++){
set<int> ans;
for(int j = head[i];j != -1;j = edge[j].next){
int v = edge[j].to;
if(scc[i] == scc[v]) ans.insert(v - n);
}
cout << ans.size();
for(auto j : ans) cout << " " << j;
cout << endl;
}
}
return 0;
}