-
Notifications
You must be signed in to change notification settings - Fork 18
/
min_cost_flow.rs
218 lines (201 loc) · 7.22 KB
/
min_cost_flow.rs
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
pub mod primal_dual {
use std::cmp;
use std::collections::BinaryHeap;
type Flow = i64;
type Cost = i64;
const INF: Cost = 1 << 60;
struct Edge {
to: usize,
capacity: Flow,
flow: Flow,
cost: Cost,
reverse_to: usize,
}
impl Edge {
fn residue(&self) -> Flow {
self.capacity - self.flow
}
}
pub struct MinimumCostFlowSolver {
graph: Vec<Vec<Edge>>,
previous_edge: Vec<(usize, usize)>,
}
impl MinimumCostFlowSolver {
pub fn new(n: usize) -> Self {
MinimumCostFlowSolver {
graph: (0..n).map(|_| Vec::new()).collect(),
previous_edge: vec![(0, 0); n],
}
}
pub fn add_edge(&mut self, from: usize, to: usize, capacity: Flow, cost: Cost) {
let reverse_from = self.graph[to].len();
let reverse_to = self.graph[from].len();
self.graph[from].push(Edge {
to,
capacity,
flow: 0,
cost,
reverse_to: reverse_from,
});
self.graph[to].push(Edge {
to: from,
capacity,
flow: capacity,
cost: -cost,
reverse_to,
});
}
/// Find the minimum cost to send `flow` through a flow network from `source` to `sink`.
pub fn solve(&mut self, source: usize, sink: usize, mut flow: Flow) -> Option<Flow> {
let n = self.graph.len();
let mut result = 0;
let mut h = vec![0; n];
let mut q: BinaryHeap<(Cost, usize)> = BinaryHeap::new();
while flow > 0 {
let mut dist = vec![INF; n];
dist[source] = 0;
q.push((0, source));
while let Some((current_dist, v)) = q.pop() {
if dist[v] < current_dist {
continue;
}
for (i, e) in self.graph[v].iter().enumerate() {
if e.residue() == 0 {
continue;
}
if dist[e.to] + h[e.to] > current_dist + h[v] + e.cost {
dist[e.to] = current_dist + h[v] + e.cost - h[e.to];
self.previous_edge[e.to] = (v, i);
q.push((dist[e.to], e.to));
}
}
}
if dist[sink] == INF {
return None;
}
for i in 0..n {
h[i] += dist[i];
}
let mut df = flow;
let mut v = sink;
while v != source {
let (prev_v, prev_e) = self.previous_edge[v];
df = cmp::min(df, self.graph[prev_v][prev_e].residue());
v = prev_v;
}
flow -= df;
result += df * h[sink];
let mut v = sink;
while v != source {
let (prev_v, prev_e) = self.previous_edge[v];
self.graph[prev_v][prev_e].flow += df;
let reversed_edge_id = self.graph[prev_v][prev_e].reverse_to;
self.graph[v][reversed_edge_id].flow -= df;
v = prev_v;
}
}
Some(result)
}
/// Find the minimum cost to send `flow` through a flow network, which contains edges of
/// negative cost, from `source` to `sink`.
pub fn neg_solve(&mut self, source: usize, sink: usize, mut flow: Flow) -> Option<Flow> {
let n = self.graph.len();
let mut result = 0;
while flow > 0 {
let mut dist = vec![INF; n];
dist[source] = 0;
loop {
let mut updated = false;
for v in 0..n {
if dist[v] == INF {
continue;
}
for (i, e) in self.graph[v].iter().enumerate() {
if e.residue() == 0 {
continue;
}
if dist[e.to] > dist[v] + e.cost {
dist[e.to] = dist[v] + e.cost;
self.previous_edge[e.to] = (v, i);
updated = true;
}
}
}
if !updated {
break;
}
}
if dist[sink] == INF {
return None;
}
let mut df = flow;
let mut v = sink;
while v != source {
let (prev_v, prev_e) = self.previous_edge[v];
df = cmp::min(df, self.graph[prev_v][prev_e].residue());
v = prev_v;
}
flow -= df;
result += df * dist[sink];
let mut v = sink;
while v != source {
let (prev_v, prev_e) = self.previous_edge[v];
self.graph[prev_v][prev_e].flow += df;
let reversed_edge_id = self.graph[prev_v][prev_e].reverse_to;
self.graph[v][reversed_edge_id].flow -= df;
v = prev_v;
}
}
Some(result)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::utils::test_helper::Tester;
#[test]
fn solve_grl_6_b() {
let tester = Tester::new("./assets/GRL_6_B/in/", "./assets/GRL_6_B/out/");
tester.test_solution(|sc| {
let v: usize = sc.read();
let e: usize = sc.read();
let f: i64 = sc.read();
let mut solver = primal_dual::MinimumCostFlowSolver::new(v);
for _ in 0..e {
let u: usize = sc.read();
let v: usize = sc.read();
let c: i64 = sc.read();
let d: i64 = sc.read();
solver.add_edge(u, v, c, d);
}
let ans = match solver.solve(0, v - 1, f) {
Some(flow) => flow,
None => -1,
};
sc.write(format!("{}\n", ans));
});
}
#[test]
fn solve_grl_6_b_negative() {
let tester = Tester::new("./assets/GRL_6_B/in/", "./assets/GRL_6_B/out/");
tester.test_solution(|sc| {
let v: usize = sc.read();
let e: usize = sc.read();
let f: i64 = sc.read();
let mut solver = primal_dual::MinimumCostFlowSolver::new(v);
for _ in 0..e {
let u: usize = sc.read();
let v: usize = sc.read();
let c: i64 = sc.read();
let d: i64 = sc.read();
solver.add_edge(u, v, c, d);
}
let ans = match solver.neg_solve(0, v - 1, f) {
Some(flow) => flow,
None => -1,
};
sc.write(format!("{}\n", ans));
});
}
}