题目链接
利用环的性质,我们依然可以建立二分图,进行KM即可。
#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>
#include <limits>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <unordered_map>
#include <unordered_set>
#define lowbit(x) ( x&(-x) )
#define pi 3.141592653589793
#define e 2.718281828459045
#define INF 0x3f3f3f3f
#define HalF (l + r)>>1
#define lsn rt<<1
#define rsn rt<<1|1
#define Lson lsn, l, mid
#define Rson rsn, mid+1, r
#define QL Lson, ql, qr
#define QR Rson, ql, qr
#define myself rt, l, r
#define MP(a, b) make_pair(a, b)
#define Min3(a, b, c) min(a, min(b, c))
using namespace std;
typedef unsigned long long ull;
typedef unsigned int uit;
typedef long long ll;
const int maxN = 1e3 + 7;
int N, M;
struct KM
{
int n, mp[maxN][maxN], link_x[maxN], link_y[maxN];
bool vis_x[maxN], vis_y[maxN];
int que[maxN], top, fail, pre[maxN];
ll hx[maxN], hy[maxN], slk[maxN];
bool check(int i)
{
vis_x[i] = true;
if(link_x[i])
{
que[fail++] = link_x[i];
vis_y[link_x[i]] = true;
return true;
}
while(i)
{
link_x[i] = pre[i];
swap(i, link_y[pre[i]]);
}
return false;
}
void bfs(int S)
{
for(int i=1; i<=n; i++)
{
slk[i] = INF;
vis_x[i] = vis_y[i] = false;
}
top = 0; fail = 1; que[0] = S;
vis_y[S] = true;
while(true)
{
ll d = 0;
while(top < fail)
{
for(int i=1, j = que[top++]; i<=n; i++)
{
if(!vis_x[i] && slk[i] >= (d = hx[i] + hy[j] - mp[i][j]))
{
pre[i] = j;
if(d) slk[i] = d;
else if(!check(i)) return;
}
}
}
d = INF;
for(int i=1; i<=n; i++)
{
if(!vis_x[i] && d > slk[i]) d = slk[i];
}
for(int i=1; i<=n; i++)
{
if(vis_x[i]) hx[i] += d;
else slk[i] -= d;
if(vis_y[i]) hy[i] -= d;
}
for(int i=1; i<=n; i++)
{
if(!vis_x[i] && !slk[i] && !check(i)) return;
}
}
}
void init()
{
for(int i=1; i<=n; i++)
{
link_x[i] = link_y[i] = 0;
hy[i] = slk[i] = 0;
vis_y[i] = false;
}
for(int i=1; i<=n; i++)
{
hx[i] = 0;
for(int j=1; j<=n; j++)
{
if(hx[i] < mp[i][j]) hx[i] = mp[i][j];
}
}
}
void solve()
{
n = N;
init();
for(int i=1; i<=n; i++) bfs(i);
ll ans = 0;
for(int i=1; i<=n; i++) ans += hx[i] + hy[i];
if(ans > -INF) printf("%lld\n", -ans);
else printf("NO\n");
}
}km;
int main()
{
int T; scanf("%d", &T);
for(int Cas=1; Cas <= T; Cas++)
{
scanf("%d%d", &N, &M);
for(int i=1; i<=N; i++) for(int j=1; j<=N; j++) km.mp[i][j] = -INF;
for(int i=1, u, v, w; i<=M; i++)
{
scanf("%d%d%d", &u, &v, &w);
km.mp[u][v] = km.mp[v][u] = max(km.mp[u][v], -w);
}
printf("Case %d: ", Cas);
km.solve();
}
return 0;
}