最优权匹配问题

package com.bluecup.org;

import java.util.Arrays;
import java.util.Scanner;

public class KM {

	/**
	 * @param args
	 */
	static int n;
	static int lx[] = new int[10];
	static int ly[] = new int[10];
	static int d[][] = new int[10 + 1][10 + 1];

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		Scanner scan = new Scanner(System.in);
		int value;
		n = scan.nextInt();
		for (int i = 1; i <= n; i++)
			Arrays.fill(d[i], -1);
		do {
			int i = scan.nextInt();
			int j = scan.nextInt();
			value = scan.nextInt();
			if (value > 0)
				d[i][j] = value;
		} while (value > 0);
		lx_max();
		Arrays.fill(ly, 0);
		KM_match();
	}

	static boolean edge[][] = new boolean[10][10];
	static boolean xmatch[] = new boolean[10];
	static boolean ymatch[] = new boolean[10];
	static int match[] = new int[10];

	private static void KM_match() {
		// TODO Auto-generated method stub
		while (true) {
			// 初始edge
			// 初始match
			// 匈牙利算法
			// 是否退出
			// 找最小顶标差值
			// 减去值,调整顶标
			for (int i = 1; i <= n; i++) {
				for (int j = 1; j <= n; j++)
					if (d[i][j] == lx[i] + ly[j]) {
						edge[i][j] = true;
					} else
						edge[i][j] = false;
			}
			for (int i = 1; i <= n; i++)
				match[i] = -1;
			int value = 0;
			for (int i = 1; i <= n; i++) {
				for (int j = 1; j <= n; j++) {
					xmatch[j] = false;
					ymatch[j] = false;
				}
				if (hungary(i)) {
					value++;
				} else {
					xmatch[i] = true;
					break;
				}
			}
			if (value >= n)
				break;
			int ex;
			ex = Integer.MAX_VALUE;
			for (int i = 1; i <= n; i++) {

				for (int j = 1; j <= n && xmatch[i]; j++) {

					if (!ymatch[j] && ex > (lx[i] + ly[j] - d[i][j])) {
						ex = lx[i] + ly[j] - d[i][j];
					}
				}
			}
			for (int i = 1; i <= n; i++) {
				if (xmatch[i]) {
					lx[i] = lx[i] - ex;
				}
				if (ymatch[i]) {
					ly[i] = ly[i] + ex;
				}
			}
		}

		int cost = 0;
		for (int i = 1; i <= n; i++) {
			cost += d[match[i]][i];
		}
		System.out.println(cost + "最大值");
	}

	private static boolean hungary(int x) {
		// TODO Auto-generated method stub
		for (int i = 1; i <= n; i++) {
			if (!ymatch[i] && edge[x][i]) {
				ymatch[i] = true;
				if (match[i] == -1 || hungary(match[i])) {
					match[i] = x;
					return true;
				}
				if (match[i] != -1)
					xmatch[match[i]] = true;
			}
		}
		return false;
	}

	private static void lx_max() {
		// TODO Auto-generated method stub
		for (int i = 1; i <= n; i++) {
			lx[i] = Integer.MIN_VALUE;
			for (int j = 1; j <= n; j++) {
				if (lx[i] < d[i][j])
					lx[i] = d[i][j];
			}
		}
	}

}


 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值