同HDU 1853 & 3488,最小费用圈覆盖。
只不过这一次是无向边,所以在建图时建立双向边即可。
图的完备匹配实际上就是n个环的并。
/*HDU 1853*/
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <string>
#include <cstring>
#include <cmath>
#include <vector>
#include <queue>
#include <algorithm>
#include <map>
using namespace std;
const int maxn = 1010;
const int INF = 0x3f3f3f3f;
int n, m;
int W[maxn][maxn];
int Lx[maxn], Ly[maxn];
int Left[maxn];
bool S[maxn], T[maxn];
bool match(int i)
{
S[i] = 1;
for(int j = 1; j <= m; j++) if(Lx[i]+Ly[j] == W[i][j] && !T[j])
{
T[j] = 1;
if(!Left[j] || match(Left[j]))
{
Left[j] = i;
return 1;
}
}
return 0;
}
void update()
{
int a = INF;
for(int i = 1; i <= n; i++) if(S[i])
for(int j = 1; j <= m; j++) if(!T[j])
a = min(a, Lx[i]+Ly[j]-W[i][j]);
for(int i = 1; i <= n; i++)
{
if(S[i]) Lx[i] -= a;
}
for(int j = 1; j <= m; j++)
{
if(T[j]) Ly[j] += a;
}
}
void KM()
{
memset(Left, 0, sizeof(Left));
memset(Lx, 0, sizeof(Lx));
memset(Ly, 0, sizeof(Ly));
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= m; j++)
Lx[i] = max(Lx[i], W[i][j]);
}
for(int i = 1; i <= n; i++)
{
for(;;)
{
for(int j = 1; j <= m; j++) S[j] = T[j] = 0;
if(match(i)) break; else update();
}
}
}
inline void readint(int &x)
{
char c;
c = getchar();
while(!isdigit(c)) c = getchar();
x = 0;
while(isdigit(c)) x = x*10+c-'0', c = getchar();
}
inline void writeint(int x)
{
if(x > 9) writeint(x/10);
putchar(x%10+'0');
}
int N, M;
void read_case()
{
readint(N), readint(M);
n = m = N;
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++) W[i][j] = -INF;
for(int i = 1; i <= M; i++)
{
int u, v, w;
readint(u), readint(v), readint(w);
W[u][v] = W[v][u] = max(W[u][v], -w);
}
}
int cal()
{
int ans = 0;
for(int i = 1; i <= m; i++)
{
if(Left[i] != 0 && W[Left[i]][i] != -INF) ans -= W[Left[i]][i];
else return -1;
}
return ans;
}
int times;
void solve()
{
read_case();
KM();
int ans = cal();
if(ans == -1) printf("Case %d: NO\n", ++times);
else { printf("Case %d: ", ++times); writeint(ans), puts(""); }
}
int main()
{
int T;
times = 0;
for(readint(T); T > 0; T--)
{
solve();
}
return 0;
}