HDU 3488 Tour KM完美匹配

一、内容

 In the kingdom of Henryy, there are N (2 <= N <= 200) cities, with M (M <= 30000) one-way roads connecting them. You are lucky enough to have a chance to have a tour in the kingdom. The route should be designed as: The route should contain one or more loops. (A loop is a route like: A->B->……->P->A.)
Every city should be just in one route.
A loop should have at least two cities. In one route, each city should be visited just once. (The only exception is that the first and the last city should be the same and this city is visited twice.)
The total distance the N roads you have chosen should be minimized.

Input

An integer T in the first line indicates the number of the test cases.
In each test case, the first line contains two integers N and M, indicating the number of the cities and the one-way roads. Then M lines followed, each line has three integers U, V and W (0 < W <= 10000), indicating that there is a road from U to V, with the distance of W.
It is guaranteed that at least one valid arrangement of the tour is existed.
A blank line is followed after each test case.

Output

For each test case, output a line with exactly one integer, which is the minimum total distance.

Sample Input

1
6 9
1 2 5
2 3 5
3 1 10
3 4 12
4 1 8
4 6 11
5 4 7
5 6 9
6 5 4

Sample Output

42

二、思路

  • 从某点出发再回到某点,求图中环权值和最小。
  • 在这里插入图片描述

三、代码

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 205, INF = 0x3f3f3f3f;
int n, m, t, u, v, w[N][N], la[N], a, lb[N], mat[N], d, upd[N];
bool va[N], vb[N];
bool dfs(int u) {
	va[u] = true; 
	for (int v = 1; v <= n; v++) {
		if (vb[v]) continue;
		if (la[u] + lb[v] - w[u][v] == 0) {
			vb[v] = true;
			if (!mat[v] || dfs(mat[v])) {
				mat[v] = u;
				return true;
			}
		} else upd[v] = min(upd[v], la[u] + lb[v] - w[u][v]);
	} 
	return false;
}
int KM() {
	memset(mat, 0, sizeof(mat));
	for (int i = 1; i <= n; i++) {
		la[i] = -INF;
		lb[i] = 0;
		for (int j = 1; j <= n; j++) {
			la[i] = max(la[i], w[i][j]); 
		}	
	}
	for (int i = 1; i <= n; i++) {
		while (1) {
			memset(va, false, sizeof(va));
			memset(vb, false, sizeof(vb));
			for (int j = 1; j <= n; j++) upd[j] = INF;
			if (dfs(i)) break;
			//降低期望
			d = INF;
			for (int j = 1; j <= n; j++) if (!vb[j]) d = min(d, upd[j]);
			for (int j = 1; j <= n; j++) {
				if (va[j]) la[j] -= d;
				if (vb[j]) lb[j] += d;
			} 
		}
	}
	int ans = 0;
	for (int i = 1; i <= n; i++) ans += w[mat[i]][i];
	return -ans; 
}
int main() {
	scanf("%d", &t);
	while (t--) {
		scanf("%d%d", &n, &m);
		memset(w, -0x3f, sizeof(w));
		for (int i = 1; i <= m; i++) {
			scanf("%d%d%d", &u, &v, &a);
			w[u][v] = max(-a, w[u][v]); 
		}
		printf("%d\n", KM());
	}
	return 0;
} 
发布了482 篇原创文章 · 获赞 492 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/qq_41280600/article/details/104562865