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 <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <set>
#include <queue>
#include <algorithm>
#include <vector>
#include <cstdlib>
#include <cmath>
#include <ctime>
#include <stack>
#define ll long long
#define clr(x) memset(x,0,sizeof(x))
using namespace std;
const int INF = 0x3f3f3f3f;
int N,M;
int w[205][205];
int lx[205],ly[205],sx[205],sy[205],match[205],slack[205];
int path(int u) {
sx[u] = 1;
for(int i = 1; i <= N; ++i) {
if(sy[i]) continue;
int t = lx[u] + ly[i] - w[u][i];
if(!t) {
sy[i] = 1;
if(!match[i] || path(match[i])) {
match[i] = u;
return true;
}
}
else slack[i] = min(slack[i], t);
}
return false;
}
int main() {
int T, x, y, ct;
scanf("%d", &T);
while(T--) {
scanf("%d %d", &N, &M);
memset(w, 0x80, sizeof (w));
for(int i = 1; i <= M; ++i) {
scanf("%d %d %d", &x, &y, &ct);
w[x][y] = max(w[x][y], -ct);
}
memset(match, 0, sizeof (match));
memset(lx, 0x80, sizeof (lx));
memset(ly, 0, sizeof (ly));
for(int i = 1; i <= N; ++i)
for(int j = 1; j <= N; ++j)
lx[i] = max(lx[i], w[i][j]);
for(int i = 1; i <= N; ++i) {
memset(slack, 0x3f, sizeof (slack));
while(1) {
memset(sx, 0, sizeof (sx));
memset(sy, 0, sizeof (sy));
if (path(i)) break;
int d = INF;
for(int j = 1; j <= N; ++j) if (!sy[j]) d = min(d, slack[j]);
for(int j = 1; j <= N; ++j) {
if (sx[j]) lx[j] -= d;
if (sy[j]) ly[j] += d;
else slack[j] -= d;
}
}
}
int ret = 0;
for(int i = 1; i <= N; ++i) ret += w[match[i]][i];
printf("%d\n", -ret);
}
return 0;
}
本文介绍了一种解决特定旅行商问题的方法,该问题是找到一系列单向路径,使得每个城市恰好被访问一次并形成一个环路,同时使得所选路径的总距离最小。通过使用匈牙利算法来匹配城市之间的路径,最终输出最小总距离。

被折叠的 条评论
为什么被折叠?



