题目:http://vjudge.net/problem/UVA-11183
题意:以0为根构建一个最小树形图,求最小花费
思路:裸题,没什么好说的
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <cmath>
#include <queue>
#include <map>
using namespace std;
const int N = 1010, INF = 0x3f3f3f3f;
struct edge
{
int v, u, cost;
}g[N*40];
int n, m, cas;
int in[N], pre[N], id[N], vis[N];
int ma(int s, int n, int m)
{
int res = 0;
while(true)
{
for(int i = 0; i < n; i++) in[i] = INF;
for(int i = 0; i < m; i++)
{
int v = g[i].v, u = g[i].u;
if(v != u && g[i].cost < in[u]) in[u] = g[i].cost, pre[u] = v;
}
for(int i = 0; i < n; i++)
{
if(i == s) continue;
if(in[i] == INF) return -1;
}
int num = 0;
memset(id, -1, sizeof id);
memset(vis, -1, sizeof vis);
in[s] = 0;
for(int i = 0; i < n; i++)
{
res += in[i];
int v = i;
while(vis[v] != i && id[v] == -1 && v != s) vis[v] = i, v = pre[v];
if(v != s && id[v] == -1)
{
for(int j = pre[v]; j != v; j = pre[j]) id[j] = num;
id[v] = num++;
}
}
if(num == 0) break;
for(int i = 0; i < n; i++)
if(id[i] == -1) id[i] = num++;
for(int i = 0; i < m; i++)
{
int v = g[i].v, u = g[i].u;
g[i].v = id[v], g[i].u = id[u];
if(id[v] != id[u]) g[i].cost -= in[u];
}
n = num, s = id[s];
}
return res;
}
int main()
{
int t;
scanf("%d", &t);
while(t--)
{
scanf("%d%d", &n, &m);
for(int i = 0; i < m; i++) scanf("%d%d%d", &g[i].v, &g[i].u, &g[i].cost);
int res = ma(0, n, m);
if(res != -1) printf("Case #%d: %d\n", ++cas, res);
else printf("Case #%d: Possums!\n", ++cas);
}
return 0;
}