题目大意:
n个王子n个女孩,每个王子喜欢一些编号的女孩,问在确保每个王子能找到女孩的情况下每个王子各能选择哪些女孩?题目还给出了一种完美匹配的选择情况。
解题思路:
刚开始自己想的是二分图匹配暴力跑情况= = ,不过肯定过不了就没写。
这道题目真的是神题,把二分图匹配问题转换成了强连通分量来解,不过目前对于这两个知识点都是一知半解,所以了解的不是很清楚。在此贴出证明过程:证明过程
其实这个题目有一个坑点,额,在此就不说是什么了,放一组数据在代码最后。
Ac代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<map>
#include<queue>
#include<stack>
#include<set>
#include<cmath>
#include<vector>
#define lson rt<<1
#define rson rt<<1|1
using namespace std;
typedef long long ll;
const int maxn=4e3+5;
const int INF=1e9+7;
const ll mod=998244353;
int n,m,tot,cnt,dfn[maxn],low[maxn],belong[maxn];
vector<int> v[maxn],ans[maxn],res;
bool vis[maxn];
stack<int> s;
void tarjan(int u)
{
dfn[u]=low[u]=++tot;
vis[u]=1,s.push(u);
for(int i=0;i<v[u].size();i++)
{
int g=v[u][i];
if(!dfn[g])
{
tarjan(g);
low[u]=min(low[u],low[g]);
}
else if(vis[g]) low[u]=min(low[u],dfn[g]);
}
if(dfn[u]==low[u])
{
cnt++;
res.clear();
while(!s.empty())
{
int now=s.top();
s.pop();vis[now]=0;
res.push_back(now);
belong[now]=cnt;
if(now==u) break;
}
for(int i=0;i<res.size();i++) //处理出每个王子的公主
{
if(res[i]<=n)
{
for(int j=0;j<v[res[i]].size();j++)
{
if(belong[v[res[i]][j]]==cnt&&v[res[i]][j]>n)
ans[res[i]].push_back(v[res[i]][j]);
}
}
}
}
}
void print() //输出每个王子所对应的公主
{
for(int i=1;i<=n;i++)
{
int res=0;
sort(ans[i].begin(),ans[i].end());
for(int j=0;j<ans[i].size();j++) if(ans[i][j]<=n) res++;
printf("%d",ans[i].size()-res);
for(int j=0;j<ans[i].size();j++)
if(ans[i][j]>n) printf(" %d",ans[i][j]-n);
printf("\n");
}
}
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
int m,x;
scanf("%d",&m);
for(int j=0;j<m;j++) //这里注意x+n
{
scanf("%d",&x);
v[i].push_back(x+n);
}
}
for(int i=1;i<=n;i++)
{
int x;
scanf("%d",&x);
v[x+n].push_back(i);
}
for(int i=1;i<=n;i++)
if(!dfn[i]) tarjan(i);
print();
//system("pause");
}
/*
input
3
2 1 2
3 1 2 3
2 2 3
1 2 3
ouput
2 1 2
3 1 2 3
2 2 3
*/