km算法

作用

求二分图最大权完美匹配

参考博客

KM算法详解+模板

代码实现

存储结构

const int maxn=310;
const int inf=0x3f3f3f3f;
int mmp[maxn][maxn]; // 记录每个妹子和每个男生的好感度
bool book_gril[maxn];//标记被匹配过的人
bool book_boy[maxn];
int val_gril[maxn];//权值
int val_boy[maxn];
int match[maxn];//记录匹配到的人
int slack[maxn];//尚需的期望值

所需函数

dfs递归匹配
bool dfs(int gril){
	book_gril[gril]=true;
	for(int boy=0;boy<n;boy++){
		if(book_boy[boy]) continue;// 每一轮匹配每个男生只尝试一次
		int x=val_gril[gril]+val_boy[boy]-mmp[gril][boy];//计算值是否匹配
		if(x==0){//如果匹配
			book_boy[boy]=true;
			if(match[boy]==-1||dfs(match[boy])){// 找到一个没有匹配的男生 或者该男生的妹子可以找到其他人
				match[boy]=gril;
				return true;
			}
			
		}
		else{
			slack[boy]=min(slack[boy],x); // slack 男生要得到女生的倾心还需多少期望值取最小
		}
	}
	return false;
}
km函数
int km(){
	memset(match,-1,sizeof(match));
	memset(val_boy,0,sizeof(val_boy));
	for(int i=0;i<n;i++){
		val_gril[i]=mmp[i][0];
		for(int j=1;j<n;j++){
			val_gril[i]=max(val_gril[i],mmp[i][j]);// 初始化每个女生期望值是与她相连的男生最大的好感度
		}
	}
	 // 尝试为每一个女生解决归宿问题
	for(int i=0;i<n;i++){
		fill(slack,slack+n,inf);// 因为要取最小值 初始化为无穷大
		while(1){
			memset(book_gril,false,sizeof(book_gril));
			memset(book_boy,false,sizeof(book_boy));
			if(dfs(i)) break;// 找到归宿 退出
			int v=inf;
			// 最小可降低的期望值
			for(int j=0;j<n;j++)if(!book_boy[j]) v=min(v,slack[j]);
			for(int j=0;j<n;j++){
				 // 所有访问过的女生降低期望值
				if(book_gril[j]) val_gril[j]-=v;
				 // 所有访问过的男生增加期望值
				if(book_boy[j]) val_boy[j]+=v;
				else slack[j]-=v;
			}
		}
	}
	 // 匹配完成 求出所有配对的好感度的和
	int ans=0;
	for(int i=0;i<n;i++) ans+=mmp[match[i]][i];
	return ans;
}
main函数
int main(){
	while(~scanf("%d",&n)){
		for(int i=0;i<n;i++)
			for(int j=0;j<n;j++){
				scanf("%d",&mmp[i][j]);
			}
			printf("%d\n",km());
	}
}

例题

1、HDU - 2255 奔小康赚大钱
AC代码
#include<bits/stdc++.h>
using namespace std;
const int maxn=310;
const int inf=0x3f3f3f3f;
int mmp[maxn][maxn];
bool book_gril[maxn];
bool book_boy[maxn];
int val_gril[maxn];
int val_boy[maxn];
int match[maxn];
int slack[maxn];
int n;
bool dfs(int gril){
	book_gril[gril]=true;
	for(int boy=0;boy<n;boy++){
		if(book_boy[boy]) continue;
		int x=val_gril[gril]+val_boy[boy]-mmp[gril][boy];
		if(x==0){
			book_boy[boy]=true;
			if(match[boy]==-1||dfs(match[boy])){
				match[boy]=gril;
				return true;
			}
			
		}
		else{
			slack[boy]=min(slack[boy],x);
		}
	}
	return false;
}
int km(){
	memset(match,-1,sizeof(match));
	memset(val_boy,0,sizeof(val_boy));
	for(int i=0;i<n;i++){
		val_gril[i]=mmp[i][0];
		for(int j=1;j<n;j++){
			val_gril[i]=max(val_gril[i],mmp[i][j]);
		}
	}
	for(int i=0;i<n;i++){
		fill(slack,slack+n,inf);
		while(1){
			memset(book_gril,false,sizeof(book_gril));
			memset(book_boy,false,sizeof(book_boy));
			if(dfs(i)) break;
			int v=inf;
			for(int j=0;j<n;j++)if(!book_boy[j]) v=min(v,slack[j]);
			for(int j=0;j<n;j++){
				if(book_gril[j]) val_gril[j]-=v;
				if(book_boy[j]) val_boy[j]+=v;
				else slack[j]-=v;
			}
		}
	}
	int ans=0;
	for(int i=0;i<n;i++) ans+=mmp[match[i]][i];
	return ans;
}
int main(){
	while(~scanf("%d",&n)){
		for(int i=0;i<n;i++)
			for(int j=0;j<n;j++){
				scanf("%d",&mmp[i][j]);
			}
			printf("%d\n",km());
	}
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是 MATLAB 中的 KM(Kuhn-Munkres)算法代码: ```matlab function [assignment,cost] = KM(costMat) % KM Solve the linear assignment problem with the Kuhn-Munkres algorithm % [ASSIGN,COST] = KM(COSTMAT) returns the optimal column indices, ASSIGN % assigned to each row and the minimum COST based on the assignment % problem represented by the COSTMAT, where the (i,j)th element represents % the cost to assign the jth job to the ith worker. % % This is vectorized implementation of the algorithm. It is the fastest % implementation of the KM algorithm in MATLAB. % % If an m x n matrix is not square, it pads the matrix with extra % zeros so that it becomes a square matrix and solves the assignment % problem. % % Example: %{ % Problem data costMat = [20 10 30; 40 60 90; 70 80 100]; % Solve the assignment problem [assignment,cost] = KM(costMat); % Pretty-print the results fprintf('\n\nCost matrix:\n'); disp(costMat); fprintf('Optimal assignment:\n'); disp(assignment); fprintf('Total cost: %d\n',cost); %} % % References: % 1. http://csclab.murraystate.edu/~bob.pilgrim/445/munkres.html % 2. http://en.wikipedia.org/wiki/Hungarian_algorithm % Assign jobs to workers to minimize cost costMat = double(costMat); [nRows,nCols] = size(costMat); bigM = 10^6*max(costMat(:)); costMat(costMat==Inf) = bigM; % If the matrix isn't square, pad it with zeros if nRows ~= nCols if nRows > nCols costMat(:,nRows) = 0; nCols = nRows; else costMat(nCols,nCols) = 0; nRows = nCols; end end % Subtract off row minima and check whether input is feasible minR = min(costMat,[],2); costMat = bsxfun(@minus,costMat,minR); minC = min(costMat,[],1); costMat = bsxfun(@minus,costMat,minC); % Allocate storage for the starred zeros and their covers rowCover = false(nRows,1); colCover = false(1,nCols); starMat = false(nRows,nCols); % Main loop: Augment the matrix until it is feasible while any(~rowCover) % Find an uncovered zero [r,c] = find(~costMat & ~rowCover' & ~colCover); if isempty(r) % If there are no uncovered zeros, do some covers and try again [minVal,c] = min(costMat(~rowCover,colCover)); costMat = costMat - minVal; rowCover = bsxfun(@or,rowCover,costMat==0); colCover(c) = false; continue end % Select the uncovered zero that is in the first row or column zInd = sub2ind([nRows,nCols],r(1),c(1)); % Star the selected zero starMat(zInd) = true; % Cover the row and column of the zero rowCover(r(1)) = true; colCover(c(1)) = true; % Find starred zeros in the column starCol = starMat(:,c(1)); while any(starCol) % Find the first starred zero in the column rInd = find(starCol); zInd = sub2ind([nRows,nCols],rInd(1),c(1)); % Unstar the zero starMat(zInd) = false; % Find the corresponding primed zero cInd = find(starMat(rInd(1),:)); % Star the primed zero zInd = sub2ind([nRows,nCols],rInd(1),cInd(1)); starMat(zInd) = true; % Cover the row and column of the primed zero rowCover(rInd(1)) = true; colCover(cInd(1)) = true; % Find starred zeros in the column starCol = starMat(:,c(1)); end end % Construct the assignment and calculate its cost assignment = zeros(nRows,1); starMat = costMat == 0 & starMat; while any(starMat(:)) [r,c] = find(starMat,1); assignment(r) = c; starMat(r,:) = false; starMat(:,c) = false; end [r,c] = find(costMat == 0 & ~starMat); for i = 1:numel(r) assignment(r(i)) = c(i); end cost = sum(double(sub2ind([nRows,nCols],(1:nRows)',assignment)))... + sum(minR) + sum(minC); end ``` 你可以将上述代码保存为一个名为 "KM.m" 的文件,并在 MATLAB 中调用它。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值