首页 > 代码库 > UVA 1349 - Optimal Bus Route Design(KM完美匹配)

UVA 1349 - Optimal Bus Route Design(KM完美匹配)

UVA 1349 - Optimal Bus Route Design

题目链接

题意:给定一些有向带权边,求出把这些边构造成一个个环,总权值最小

思路:由于环入度出度为1,所以可以把每个点拆成入度点和出度点,然后建图做一次二分图完美匹配即可,注意这题坑点,有重边

代码:

#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;
		}
	}

	void 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();
			}
		}
	}

	void solve() {
		km();
		int ans = 0, flag = 0;
		for (int i = 0; i < n; i++) {
			if (g[left[i]][i] == -INF) {
				flag = 1;
				break;
			}
			ans += g[left[i]][i];
		}
		if (flag) printf("N\n");
		else printf("%d\n", -ans);
	}

} gao;

int n;

int main() {
	while (~scanf("%d", &n) && n) {
		gao.init(n);
		int a, b;
		for (int i = 0; i < n; i ++) {
			while (scanf("%d", &a)) {
				if (a == 0) break;
				scanf("%d", &b);
				a--;
				gao.add_Edge(i, a, -b);
			}
		}
		gao.solve();
	}
	return 0;
}


UVA 1349 - Optimal Bus Route Design(KM完美匹配)