4.2.2 The Perfect Stall 完美的牛栏

4.2.2 The Perfect Stall 完美的牛栏

``````5 5
2 2 5
3 2 3 4
2 1 5
3 1 2 5
1 2

``````

``````4
``````

``````#include <iostream>
using namespace std;

#define N 210

bool path[N][N];
bool isvis[N];
int match[N];
int n,m;

bool SearchPath(int s)
{
int i;
for(i=1;i<=m;i++)
{
if(path[s][i]&&!isvis[i])
{
isvis[i]=true;
if(match[i]==0||SearchPath(match[i]))
{
match[i]=s;
return true;
}
}
}
return false;
}

int main()
{
int i,j,res,cnt,tmp;
while(cin>>n>>m)
{
for(i=0;i<N;i++)
{
for(j=0;j<N;j++)
path[i][j]=false;
match[i]=0;
}
for(i=1;i<=n;i++)
{
cin>>cnt;
for(j=1;j<=cnt;j++)
{
cin>>tmp;
path[i][tmp]=true;
}
}
res=0;
for(i=1;i<=n;i++)
{
for(j=0;j<N;j++)
isvis[j]=false;
if(SearchPath(i))
res++;
}
cout<<res<<endl;
}
return 0;
}
``````

``````#include<cstdio>
#include<cstring>
#define MAXN 505
using namespace std;
struct T
{
int v;
int next;
}edge[40005];
int cnt;
int head[MAXN];
void add_edge(int u,int v)
{
edge[cnt].v = v;
edge[cnt].next = head[u];
head[u] = cnt++;
}
int cx[MAXN],cy[MAXN];
bool vis[MAXN];
int n,m;
bool dfs(int u)
{
for(int i = head[u]; i != -1; i = edge[i].next)
{
int v = edge[i].v;
if(!vis[v])
{
vis[v] = 1;
if(cy[v] == -1||dfs(cy[v]))
{
cx[u] = v;
cy[v] = u;
return true;
}
}
}
return false;
}
int maxmatch()
{
memset(cx,-1,sizeof cx);
memset(cy,-1,sizeof cy);
int ans = 0;
for(int i = 1; i <= n; i++)
{
if(cx[i] == -1)
{
memset(vis,0,sizeof vis);
ans += dfs(i);
}
}
return ans;
}
int main()
{
memset(head,-1,sizeof head);
scanf("%d%d",&n,&m);
for(int i = 1; i <= n; i++)
{
int s;
scanf("%d",&s);
for(int j = 1; j <= s; j++)
{
int a;
scanf("%d",&a);
add_edge(i,a+n);
add_edge(a+n,i);
}
}
int ans = maxmatch();
printf("%d\n",ans);
}
``````