码迷,mamicode.com
首页 > 其他好文 > 详细

HDU 1853 Cyclic Tour(KM完美匹配)

时间:2014-10-31 13:56:27      阅读:264      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   color   os   ar   for   sp   

HDU 1853 Cyclic Tour

题目链接

题意:一个有向图,边有权值,求把这个图分成几个环,每个点只能属于一个环,使得所有环的权值总和最小,求这个总和

思路:KM完美匹配,由于是环,所以每个点出度入度都是1,一个点拆成两个点,出点和入点,每个点只能用一次,这样就满足了二分图匹配,然后用KM完美匹配去就最小权值的匹配即可

代码:

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

const int MAXNODE = 105;

typedef int Type;
const Type INF = 0x3f3f3f3f;

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

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

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

	bool dfs(int i) {
		S[i] = true;
		for (int j = 0; j < n; 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;
					return true;
				}
			} else slack[j] = min(slack[j], tmp);
		}
		return false;
	}

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

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

int n, m;

int main() {
	while (~scanf("%d%d", &n, &m)) {
		gao.init(n);
		int u, v, w;
		while (m--) {
			scanf("%d%d%d", &u, &v, &w);
			u--; v--;
			gao.add_Edge(u, v, -w);
		}
		printf("%d\n", gao.km());
	}
	return 0;
}


HDU 1853 Cyclic Tour(KM完美匹配)

标签:style   blog   http   io   color   os   ar   for   sp   

原文地址:http://blog.csdn.net/accelerator_/article/details/40652479

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!