ACM学习-匈牙利匹配

匈牙利匹配先说一种简单情况,多了也是一样,比如A,B,C找对象,一开始A问B有没有对象,B说没有,OK,A告诉B以后你的对象是我,如果C也开始在周围(相连的节点)找对象,假如找到B,发现B已经有对象,就问B你周围有人单身吗,B发现A单身,就告诉A以后你的对象是我,否则再去询问A周围有没有人单身,依次类推下去,一旦找到类似A这样的单身B必须忍痛割爱承认以后他的对象是C。总结起来是这样的,一旦有节点找对象,找到的话,它访问过的节点就是一条长链,头是要找对象的节点,尾巴是单身的人,如果有中间节点的话,中间是已经有对象的人。执行完之后这条链除了头没有对象,其他人都有对象,也就是说找对象是让别人承认他的对象是我,而我自己却没对象。


// ACM学习-匈牙利匹配.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<iostream>
#include<vector>
using namespace std;


const int v = 13;
int edge[v][v] = {
//A  B  C  D  E  F  G  H  I  J  K  L  M
{ 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0 },//A
{ 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1 },//B
{ 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },//C
{ 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 },//D
{ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 },//E
{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },//F
{ 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0 },//G
{ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0 },//H
{ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 },//I
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1 },//J
{ 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0 },//K
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1 },//L
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0 }//M
};
char t[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M' };


const int n = 100;
vector<int> g[v];
int from[v], tot;
bool use[v];


bool match(int x){
for (int i = 0; i < g[x].size(); i++){
if (!use[g[x][i]])
{
use[g[x][i]] = true;
if (from[g[x][i]] == -1 || match(from[g[x][i]]))
{
if (from[g[x][i]] == -1)
{
cout << t[g[x][i]] << "老公是:" << t[x] << endl;
}
else{
cout << t[g[x][i]] << "旧老公是:" << t[from[g[x][i]]] << endl;
cout << t[g[x][i]] << "新老公是:" << t[x] << endl;
}

from[g[x][i]] = x;
return true;
}
}

}
return false;


}
int hungary(){
tot = 0;
memset(from,255,sizeof from);
for (int i = 0; i < v; i++){
memset(use,0,sizeof use);
if (match(i))tot++;
}
return tot;
}
int _tmain(int argc, _TCHAR* argv[])
{
for (int i = 0; i < v; i++){
for (int j = 0; j < v; j++){
if (edge[i][j])
g[i].push_back(j);

}
}
for (int i = 0; i < v; i++){
for (int j = 0; j < g[i].size(); j++){

cout << t[i] << ":" << t[g[i][j]] << ends<<ends;
}
cout << endl;
}
cout << "tot=" << hungary() << endl;
for (int i = 0; i < v; i++)
{
if (from[i] == -1){
cout << t[i] << "最早与 " << from[i] << endl;
}
else{
cout << t[i] << "最早与 " << t[from[i]] << endl;
}
//

}
return 0;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值