正常的匈牙利算法,只要输出mat即为方案
代码
#include<bits/stdc++.h>
using namespace std;
const int maxn=10005;
int n,m,cnt,head[maxn],mat[maxn],vis[maxn];
struct edge
{
int to,nxt;
}G[maxn];
void add(int x,int y)
{
G[++cnt].nxt=head[x]; G[cnt].to=y; head[x]=cnt;
}
bool dfs(int u)
{
for(int i=head[u];i;i=G[i].nxt)
{
int to=G[i].to;
if(!vis[to])
{
vis[to]=1;
if(!mat[to] || dfs(mat[to]))
{
mat[to]=u;
return true;
}
}
}
return false;
}
int main()
{
freopen("a.in","r",stdin);
freopen("a.out","w",stdout);
scanf("%d%d",&m,&n);
int x,y;
while(scanf("%d%d",&x,&y) && (x!=-1 || y!=-1))
{
add(x,y);
}
int ans=0;
for(int i=1;i<=n;i++)
{
memset(vis,0,sizeof(vis));
if(dfs(i))
ans++;
}
printf("%d\n",ans);
for(int i=1;i<=n;i++)
if(mat[i]) printf("%d %d\n",mat[i],i);
return 0;
}

本文详细介绍了匈牙利算法的基本原理及其在匹配问题中的应用。通过代码示例,展示了如何使用匈牙利算法解决最大匹配问题,包括数据结构的设计、深度优先搜索的运用以及算法的具体实现细节。
3万+

被折叠的 条评论
为什么被折叠?



