题意:给你一个n个顶点,m条边的带权有向图,要你把该图分成1个或多个不相交的有向环,且所有顶点都被有向环覆盖,问有向环所有权值的总和最小是多少。
题解:二分图最小权匹配——KM算法
有向环覆盖问题,对于一个二分图完美匹配,结果必然构成一个或多个不相交的环,因为每个点都作为起点和终点各出现一次。
求权值总和最小,我们把权值取相反数,结果也是相反数。
注意有重边。
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>
#include<queue>
#include<stack>
#include<cmath>
#include<vector>
#include<fstream>
#include<set>
#include<map>
#include<sstream>
#include<iomanip>
#define ll long long
using namespace std;
/* KM 算法
* 复杂度 O(nx*nx*ny)
* 求最大权匹配
* 若求最小权匹配,可将权值取相反数,结果取相反数
* 点的编号从 0 开始
*/
const int N = 210;
const int INF = 0x3f3f3f3f;
int nx, ny;//两边的点数
int g[N][N];//二分图描述
int linker[N], lx[N], ly[N];//y 中各点匹配状态, x,y 中的点标号
int slack[N];
bool visx[N], visy[N];
bool DFS(int x) {
visx[x] = true;
for (int y = 0; y < ny; y++) {
if (visy[y])continue;
int tmp = lx[x] + ly[y] - g[x][y];
if (tmp == 0) {
visy[y] = true;
if (linker[y] == -1 || DFS(linker[y])) {
linker[y] = x;
return true;
}
}
else if (slack[y] > tmp)
slack[y] = tmp;
}
return false;
}
int KM() {
memset(linker, -1, sizeof(linker));
memset(ly, 0, sizeof(ly));
for (int i = 0; i < nx; i++) {
lx[i] = -INF;
for (int j = 0; j < ny; j++)
if (g[i][j] > lx[i])
lx[i] = g[i][j];
}
for (int x = 0; x < nx; x++) {
for (int i = 0; i < ny; i++)
slack[i] = INF;
while (true) {
memset(visx, false, sizeof(visx));
memset(visy, false, sizeof(visy));
if (DFS(x))break;
int d = INF;
for (int i = 0; i < ny; i++)
if (!visy[i] && d > slack[i])
d = slack[i];
for (int i = 0; i < nx; i++)
if (visx[i])
lx[i] -= d;
for (int i = 0; i < ny; i++) {
if (visy[i])ly[i] += d;
else slack[i] -= d;
}
}
}
int res = 0;
for (int i = 0; i < ny; i++)
if (linker[i] != -1)
res += g[linker[i]][i];
return res;
}
int t, n, m, u, v, w;
int main() {
scanf("%d", &t);
while (t--) {
memset(g, -0x3f, sizeof(g));
scanf("%d%d", &n, &m);
for (int i = 1; i <= m; i++) {
scanf("%d%d%d", &u, &v, &w);
g[u - 1][v - 1] = max(g[u - 1][v - 1], -w);
}
nx = ny = n;
printf("%d\n", -KM());
}
return 0;
}