uva 11183 Teen Girl Squad

本文从WordPress迁移而来, 查看全部WordPress迁移文章

最小树形图模板题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
#define N 1010
#define M 40010
#define INF 0x3f3f3f3f
#define cl memset

int n,tot;
struct edge{
int u,v,w,next;
}e[M];
int in[N],id[N],pre[N],vis[N];

int Directed_MST(int root,int nv,int ne){
int res = 0;
while(true){
cl(in,0x3f,sizeof(in));
for(int i = 0; i < ne; i++){
int u = e[i].u , v = e[i].v;
if(u != v && e[i].w < in[v]){
in[v] = e[i].w; pre[v] = u;
}
}
for(int i = 0; i < nv; i++){
if(i == root) continue;
if(in[i] == INF) return -1;
}

in[root] = 0;
cl(id,-1,sizeof(id));
cl(vis,-1,sizeof(vis));
int cntnode = 0;
for(int i = 0; i < nv; i++){
int v = i;
res += in[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++;
for(int i = 0; i < ne; i++){
int temp = 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].w -= in[temp];
}
nv = cntnode;
root = id[root];
}
return res;
}

int main(){
int m,cas;
scanf("%d",&cas);
for(int c = 1; c <= cas; c++){
tot = 0;
scanf("%d%d",&n,&m);
while(m--){
scanf("%d%d%d",&e[tot].u,&e[tot].v,&e[tot].w);
tot++;
}
int ans = Directed_MST(0,n,tot);
printf("Case #%d: ",c);
if(ans == -1) puts("Possums!");
else printf("%d\n",ans);
}
return 0;
}