二分匹配,求最大匹配
之前学了链式前向星,一直没用过,现在拿来试试,不会链式前向星的可以去我博客看看,点击打开链接
- 问题描述
-
Do you ever remember the classic game - Counter-Strike?
STANMASH is a team member of a CS Team.
Today his team is against another team.
Before the starting, STANMASH, the leader of the team, decided to analyze the Combat Effectiveness of each team member. He found that - member A can kill someone in another team; member B can kill someone in another team, etc.
So he made a list that who can kill whom. We assume that one member only can kill one enemy in that map.
How many enemies can they kill in maximum? (We assume that STANMASH's team is larger than or the same as another's, but they can only let the same number as the enemy team member to play this match).
- 输入
-
This problem contains several cases.
The first line of each case is two integers N and M (1 <= M <= N <= 500), indicate the number of STANMASH team's members and another team's members.
Then follow N lines. The first integer of ith line Ki indicates the number of enemies that ith team member can kill (0 <= Ki <= M). Then follow Ki integers, each integer is the ID of enemy that he can kill. (1 <= ID <= M)
- 输出
-
For each case, you should output that the maximum number of enemies that they can kill.
#include<stdio.h>
#include<string.h>
#define maxn 510
bool vis[maxn]; //记录v2的点有没有被访问过
int match[maxn];
int n,m;
struct node
{
int next,to;
}mat[maxn*maxn];
int head[maxn*maxn];
int edgenum;
void add(int begin,int end)
{
mat[edgenum].to=end;
mat[edgenum].next=head[begin];
head[begin]=edgenum++;
}
bool dfs(int u)
{
int i;
for(i=head[u];i!=-1;i=mat[i].next)
{
int to=mat[i].to;
if(!vis[to])
{
vis[to]=1;
if(match[to]==-1 || dfs(match[to])) //如果i没出现在匹配中,或者i在匹配中,但从i的临界点出发,可以有增广路
{
match[to]=u;
return true;
}
}
}
return false;
}
int main()
{
while(~scanf("%d%d",&n,&m))
{int i,j,k,cnt;
memset(head,-1,sizeof(head));
memset(match,-1,sizeof(match));
int ans=0;
edgenum=0;
for(i=1;i<=n;i++)
{
scanf("%d",&cnt);
while(cnt--)
{
scanf("%d",&k);
add(i,k);
}
}
for(i=1;i<=n;i++)
{
memset(vis,0,sizeof(vis));
if(dfs(i))
{
ans++;
//printf("%d\n",ans);
}
}
printf("%d\n",ans);
}
return 0;
}