题目链接:UVa 11183
分析:使用朱刘算法求固定根最小树形图
代码如下:
// uva 11183
#include <cstdio>
#include <cstring>
const int N = 1111;
const int M = 44444;
const int inf = 0x7fffffff;
int pre[N], ID[N], vis[N], In[N], tot;
struct Edge
{
int u, v, cost;
} E[M];
void addedge(int a, int b, int c) { E[tot].u = a, E[tot].v = b, E[tot++].cost = c; }
// void addedge(int a, int b, int c) { E[tot++] = {a, b, c}; } // 需要支持c++11或gnu++11
int Directed_MST(int root, int NV, int NE)
{
int ret = 0;
while(true) {
// 1.找最小入边
for(int i = 0; i < NV; i++) In[i] = inf;
for(int i = 0; i < NE; i++) {
int u = E[i].u;
int v = E[i].v;
if(E[i].cost < In[v] && u != v) {
pre[v] = u;
In[v] = E[i].cost;
}
}
for(int i = 0; i < NV; i++) {
if(i == root) continue;
if(In[i] == inf) return -1; // 除了跟以外有点没有入边,则根无法到达它
}
// 2.找环
int cntnode = 0;
memset(ID, -1, sizeof(ID));
memset(vis, -1, sizeof(vis));
In[root] = 0;
for(int i = 0; i < NV; i++) { // 标记每个环
ret += In[i];
int v = i;
while(vis[v] != i && ID[v] == -1 && v != root) {
vis[v] = i;
v = pre[v];
}
if(v != root && ID[v] == -1) {
for(int u = pre[v] ; u != v ; u = pre[u]) {
ID[u] = cntnode;
}
ID[v] = cntnode++;
}
}
if(cntnode == 0) break; // 无环
for(int i = 0; i < NV; i++) {
if(ID[i] == -1) ID[i] = cntnode++;
}
// 3.缩点,重新标记
for(int i = 0; i < NE; i++) {
int v = E[i].v;
E[i].u = ID[E[i].u];
E[i].v = ID[E[i].v];
if(E[i].u != E[i].v) {
E[i].cost -= In[v];
}
}
NV = cntnode;
root = ID[root];
}
return ret;
}
int main()
{
// freopen("in", "r", stdin);
int a, b, c, n, m;
int t, k = 1;
scanf("%d", &t);
while(t--) {
tot = 0;
scanf("%d%d", &n, &m);
for(int i = 0; i < m; i++) {
scanf("%d%d%d", &a, &b, &c);
addedge(a, b, c);
}
int as = Directed_MST(0, n, m);
if(~as) printf("Case #%d: %d\n", k++, as);
else printf("Case #%d: Possums!\n", k++);
}
return 0;
}