您的位置:首页 > 其它

HDU 2063 匈牙利算法二分图的最大匹配

2014-10-05 16:18 399 查看
http://acm.hdu.edu.cn/showproblem.php?pid=2063

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
using namespace std;

int linkk[844],use[844];
int mp[844][844];
int n,m,k;
int b[844];

bool dfs(int x)
{
for(int i=1;i<=m;i++)
{
if(use[i]==0&&mp[x][i])
{
use[i]=1;
if(linkk[i]==-1||dfs(linkk[i]))
{
linkk[i]=x;
return true;
}
}
}
return false;
}

int hungary()
{
int num=0;
for(int i=1;i<=n;i++)
{
memset(use,0,sizeof(use));
if(dfs(i))
num++;
}
return num;
}

int main()
{
while(~scanf("%d",&k))
{
if(k==0)
break;
scanf("%d%d",&n,&m);
memset(mp,0,sizeof(mp));
for(int i=0;i<k;i++)
{
int u,v;
scanf("%d%d",&u,&v);
mp[u][v]=1;
}
memset(linkk,-1,sizeof(linkk));
printf("%d\n",hungary());
}
return 0;
}

利用vector容器:

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <vector>
#define MAX 1002
using namespace std;

int n,m,k;
int mat[MAX];
bool used[MAX];
vector< int > G[MAX];

bool crosspath(int k)
{
for (int i=0;i<G[k].size();i++)
{
int j=G[k][i];
if (!used[j])
{
used[j]=true;
if (mat[j]==-1 || crosspath(mat[j]))
{
mat[j]=k;
return true;
}
}
}
return false;
}

int hungary()
{
int match=0;
memset(mat,-1,sizeof(mat));
for (int i=1;i<=n;i++)
{
memset(used,0,sizeof(used));
if (crosspath(i))
match++;
}
return match;
}

int main()
{
while(~scanf("%d",&k))
{
if(k==0)break;
scanf("%d%d",&n,&m);
for(int i=0;i<=n;i++)
G[i].clear();
for(int i=0;i<k;i++)
{
int u,v;
scanf("%d%d",&u,&v);
G[u].push_back(v);
}
printf("%d\n",hungary());
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: