-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathDriected_Mst.cpp
75 lines (75 loc) · 2.36 KB
/
Driected_Mst.cpp
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
#include <cstdio>
#include <algorithm>
typedef int item;
const int inf = ~0u>>2;
const int N = 1010;
const int M = 3010;
struct Edge
{
int u, v;
int cost;
}edge[M];
int pre[N], id[M], f[N], e;
item in[N];
void add_edge(int a, int b, int cost)
{
edge[e].u = a; edge[e].v = b; edge[e].cost = cost;
e++;
}
item directed_mst(int root, int n, int m)
{
item ret = 0;
int u, v;
while(1) {
std::fill(in, in + n, inf);
for(int i = 0; i < m; i++) {
u = edge[i].u, v = edge[i].v;
if(edge[i].cost < in[v] && u != v) {
pre[v] = u;
in[v] = edge[i].cost;
}
}
for(int i = 0; i < n; i++) {
if(i != root && in[i] == inf) {
return -1;
}
}
int cirs = 0;
std::fill(id, id + n, -1);
std::fill(f, f + n, -1);
in[root] = 0;
for(int i = 0; i < n; i++) {
ret += in[i];
int v = i;
while(f[v] != i && id[v] == -1 && v != root) {
f[v] = i;
v = pre[v];
}
if(v != root && id[v] == -1) {
for(int u = pre[v]; u != v; u = pre[u]) {
id[u] = cirs;
}
id[v] = cirs++;
}
}
if(cirs == 0) {
break;
}
for(int i = 0; i < n; i++) {
if(id[i] == -1) {
id[i] = cirs++;
}
}
for(int i = 0; i < m; i++) {
v = edge[i].v;
edge[i].u = id[edge[i].u];
edge[i].v = id[edge[i].v];
if(edge[i].u != edge[i].v) {
edge[i].cost -= in[v];
}
}
n = cirs;
root = id[root];
}
return ret;
}