HDU 2853 Assignment(KM最大匹配好题)

HDU 2853 Assignment

题目链接

题意:如今有N个部队和M个任务(M>=N),每一个部队完毕每一个任务有一点的效率,效率越高越好。可是部队已经安排了一定的计划,这时须要我们尽量用最小的变动,使得全部部队效率之和最大。求最小变动的数目和变动后和变动前效率之差。

思路:对于怎样保证改变最小,没思路,看了别人题解,恍然大悟,表示想法很机智

试想,假设能让原来那些匹配边,比其它匹配出来总和同样的权值还大,对结果又不影响,那就简单了,这个看似不能做到,事实上是能够做到的

数字最多选出50个,所以把每一个数字乘上一个大于50的数字k,然后原来匹配的权值多+1,这样每k倍数字代表了原来的1,而求出来的即使有原来的多匹配的,总权值等于也不会多1,跟原来的结果一样,又保证了跟其它匹配方式相比,这个优先级更大,很的巧妙

代码:

#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;

const int MAXNODE = 55;

typedef int Type;
const Type INF = 0x3f3f3f3f;

struct KM {
	int n, m;
	Type g[MAXNODE][MAXNODE];
	Type Lx[MAXNODE], Ly[MAXNODE], slack[MAXNODE];
	int left[MAXNODE], right[MAXNODE];
	bool S[MAXNODE], T[MAXNODE];

	void init(int n, int m) {
		this->n = n;
		this->m = m;
		for (int i = 0; i < n; i++)
			for (int j = 0; j < m; j++)
				g[i][j] = -INF;
	}

	void add_Edge(int u, int v, Type val) {
		g[u][v] = val;
	}

	bool dfs(int i) {
		S[i] = true;
		for (int j = 0; j < m; j++) {
			if (T[j]) continue;
			Type tmp = Lx[i] + Ly[j] - g[i][j];
			if (!tmp) {
				T[j] = true;
				if (left[j] == -1 || dfs(left[j])) {
					left[j] = i;
					right[i] = j;
					return true;
				}
			} else slack[j] = min(slack[j], tmp);
		}
		return false;
	}

	void update() {
		Type a = INF;
		for (int i = 0; i < m; i++)
			if (!T[i]) a = min(a, slack[i]);
		for (int i = 0; i < n; i++)
			if (S[i]) Lx[i] -= a;
		for (int i = 0; i < m; i++)
			if (T[i]) Ly[i] += a;
	}

	int to[MAXNODE];

	Type km() {
		memset(left, -1, sizeof(left));
		memset(right, -1, sizeof(right));
		memset(Ly, 0, sizeof(Ly));
		for (int i = 0; i < n; i++) {
			Lx[i] = -INF;
			for (int j = 0; j < m; j++)
				Lx[i] = max(Lx[i], g[i][j]);
		}
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < m; j++) slack[j] = INF;
			while (1) {
				memset(S, false, sizeof(S));
				memset(T, false, sizeof(T));
				if (dfs(i)) break;
				else update();
			}
		}
		Type ans = 0;
		for (int i = 0; i < n; i++) {
			if (right[i] == to[i]) ans += (g[i][right[i]] - 1) / (n + 1);
			else ans += g[i][right[i]] / (n + 1);
		}
		return ans;
	}

	void solve() {
		for (int i = 0; i < n; i++)
			for (int j = 0; j < m; j++) {
				scanf("%d", &g[i][j]);
				g[i][j] *= (n + 1);
			}
		int pre = 0;
		for (int i = 0; i < n; i++) {
			scanf("%d", &to[i]);
			to[i]--;
			pre += g[i][to[i]] / (n + 1);
			g[i][to[i]]++;
		}
		int cnt = 0;
		int ans = km() - pre;
		for (int i = 0; i < n; i++) if (right[i] != to[i]) cnt++;
		printf("%d %d\n", cnt, ans);
	}
} gao;

int n, m;

int main() {
	while (~scanf("%d%d", &n, &m)) {
		gao.init(n, m);
		gao.solve();
	}
	return 0;
}


posted @ 2014-11-03 10:45  phlsheji  阅读(207)  评论(0编辑  收藏  举报