Cyclic Tour
Time limit:1000/1000 MS (java/others) Memory limit:32768/65535 K (java/others)
Total submission (s): 2674 Accepted Submission (s): 1371
Problem Description
There is N cities in our country, and M one-way roads connecting them. Now Little Tom wants to make several cyclic tours, which satisfy so, each cycle contain at least both cities, and each CI Ty belongs to one cycle exactly. Tom wants the total length of the "all" tours minimum, but he's too lazy to calculate. Can you help him?
Input
There is several test cases in the input. You should process to the end of file (EOF).
The first line of all test case contains, integers N (n≤100) and M, indicating the number of cities and the number O F Roads. The M lines followed, each of them contains three numbers A, B, and C, indicating that there are A road from city A to city B, whose length is C. (1≤a,b≤n, A≠b, 1≤c≤1000).
Output
Output one number for each test case, indicating the minimum length of the tours. If There is no such tours, output-1.
Sample Input
4 {
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
6 5
1 2 1
2 3 1
3 4 1
4 5 1
5 6 1
Sample Output
42
-1
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <
Climits> using namespace std;
#define N 505 #define MAXN 1<<28int Map[n][n];
int lx[n], ly[n];
int slack[n];
int match[n];
BOOL Visitx[n], visity[n];
int n;
BOOL Hungary (int u) {Visitx[u] = true;
for (int i = 1; I <= n; ++i) {if (visity[i]) continue;
else {if (Lx[u] + ly[i] = = Map[u][i]) {Visity[i] = true; if (match[i] = =-1 | |
Hungary (Match[i])) {Match[i] = u;
return true;
}} else Slack[i] = min (Slack[i], Lx[u] + ly[i]-map[u][i]);
}} return false;
} void Km_perfect_match () {int temp;
for (int i = 1; I <= n; ++i) lx[i] =-MAXN;
memset (ly, 0, sizeof (ly)); for (int i = 1, i <= N; ++i) for (int j =1; J <= N;
++J) Lx[i] = max (Lx[i], map[i][j]);
for (int i = 1, i <= N; ++i) {for (int j = 1; j <= N; ++j) slack[j] = MAXN;
while (1) {memset (VISITX, False, sizeof (VISITX));
Memset (visity, False, sizeof (visity));
if (Hungary (i)) break;
else {temp = MAXN;
for (int j = 1; j <= N; ++j) if (!visity[j]) temp = min (temp, slack[j]); for (int j = 1; j <= N; ++j) {if (visitx[j]) LX
[j]-= temp;
if (Visity[j]) ly[j] + = temp;
else Slack[j]-= temp;
}}}}} int main () {int m;
int A, b, cost;
int ans;
BOOL Flag;
while (scanf ("%d%d", &n, &m)! = EOF) { Ans = 0;
Flag = true;
memset (Match,-1, sizeof (match));
for (int i = 1, i <= N; ++i) for (int j = 1; j <= N; ++j) map[i][j] =-MAXN; for (int i = 1; I <= m; ++i) {scanf ("%d%d%d", &a, &b, &cost);//prevents heavy edges.
Take a smaller value (negative implementation) if (-cost > Map[a][b]) map[a][b] =-cost;
} km_perfect_match ();
for (int i = 1; I <= n; ++i)//whether there is a perfect match {if (match[i] = = 1 | | map[match[i]][i] = =-MAXN)
{flag = false;
Break
} ans + = map[match[i]][i];
} if (flag) printf ("%d\n",-ans);
else printf (" -1\n");
} return 0;
}