-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathmin_cost_circulating_flow.cpp
More file actions
392 lines (361 loc) · 13.6 KB
/
Copy pathmin_cost_circulating_flow.cpp
File metadata and controls
392 lines (361 loc) · 13.6 KB
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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
//
// Goldberg--Tarjan による cost-scaling を用いた最小費用循環流
//
// verified
// AOJ Course GRL_6_B Network Flow - Minimum Cost Flow
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=GRL_6_B&lang=jp
//
#include <bits/stdc++.h>
using namespace std;
// edge class (for min-cost flow)
template<class FLOW, class COST> struct FlowCostEdge {
// core members
int rev, from, to;
FLOW cap, icap, flow;
COST cost;
// constructor
constexpr FlowCostEdge() noexcept = default;
constexpr FlowCostEdge(int rev, int from, int to, FLOW cap, COST cost)
: rev(rev), from(from), to(to), cap(cap), icap(cap), flow(0), cost(cost) {
}
constexpr FlowCostEdge(int rev, int from, int to, FLOW cap, FLOW rcap, COST cost)
: rev(rev), from(from), to(to), cap(cap), icap(cap), flow(rcap), cost(cost) {
}
void reset() {
flow -= icap - cap;
cap = icap;
}
// debug
friend ostream& operator << (ostream& s, const FlowCostEdge& e) {
return s << e.from << " -> " << e.to << " (" << e.cap << ", " << e.flow << ", " << e.cost << ")";
}
};
// graph class (for min-cost flow)
template<class FLOW, class COST> struct FlowCostGraph {
// core members
vector<vector<FlowCostEdge<FLOW, COST>>> list;
vector<pair<int,int>> pos; // pos[i] := {vertex, order of list[vertex]} of i-th edge
vector<COST> pot; // pot[v] := potential (e.cost + pot[e.from] - pos[e.to] >= 0)
bool include_negative_edge = false;
// constructor
FlowCostGraph(int n = 0) : list(n), pot(n), include_negative_edge(false) { }
void init(int n = 0) {
list.clear(), list.resize(n);
pos.clear();
pot.assign(n, 0);
include_negative_edge = false;
}
// getter
vector<FlowCostEdge<FLOW, COST>> &operator [] (int i) {
assert(0 <= i && i < (int)list.size());
return list[i];
}
const vector<FlowCostEdge<FLOW, COST>> &operator [] (int i) const {
assert(0 <= i && i < (int)list.size());
return list[i];
}
size_t size() const noexcept {
return list.size();
}
FlowCostEdge<FLOW, COST> &get_rev_edge(const FlowCostEdge<FLOW, COST> &e) {
return list[e.to][e.rev];
}
const FlowCostEdge<FLOW, COST> &get_rev_edge(const FlowCostEdge<FLOW, COST> &e) const {
return list[e.to][e.rev];
}
FlowCostEdge<FLOW, COST> &get_edge(int i) {
return list[pos[i].first][pos[i].second];
}
const FlowCostEdge<FLOW, COST> &get_edge(int i) const {
return list[pos[i].first][pos[i].second];
}
vector<FlowCostEdge<FLOW, COST>> get_edges() const {
vector<FlowCostEdge<FLOW, COST>> edges;
for (int i = 0; i < (int)pos.size(); ++i) {
edges.push_back(get_edge(i));
}
return edges;
}
// change edges
void reset() {
for (int i = 0; i < (int)list.size(); ++i) {
for (FlowCostEdge<FLOW, COST> &e : list[i]) e.reset();
}
}
// add_edge
void add_edge(int from, int to, FLOW cap, COST cost) {
assert(0 <= from && from < (int)list.size() && 0 <= to && to < (int)list.size());
assert(cap >= 0);
int from_id = (int)list[from].size(), to_id = (int)list[to].size();
if (from == to) to_id++;
pos.emplace_back(from, from_id);
list[from].push_back(FlowCostEdge<FLOW, COST>(to_id, from, to, cap, 0, cost));
list[to].push_back(FlowCostEdge<FLOW, COST>(from_id, to, from, 0, cap, -cost));
if (cost < 0) include_negative_edge = true;
}
void add_edge(int from, int to, FLOW cap, FLOW rcap, COST cost) {
assert(0 <= from && from < (int)list.size() && 0 <= to && to < (int)list.size());
assert(cap >= 0);
int from_id = (int)list[from].size(), to_id = (int)list[to].size();
if (from == to) to_id++;
pos.emplace_back(from, from_id);
list[from].push_back(FlowCostEdge<FLOW, COST>(to_id, from, to, cap, rcap, cost));
list[to].push_back(FlowCostEdge<FLOW, COST>(from_id, to, from, rcap, cap, -cost));
if (cost < 0) include_negative_edge = true;
}
void add_bidirected_edge(int from, int to, FLOW cap, COST cost) {
assert(0 <= from && from < (int)list.size() && 0 <= to && to < (int)list.size());
assert(cap >= 0);
add_edge(from, to, cap, cap, cost);
}
// find initial potential (to resolve initial negative-edge)
// pot[v] := potential (e.cost + pot[e.from] - pos[e.to] >= 0)
bool calc_potential_dag() {
pot.assign(size(), 0);
vector<int> deg(size(), 0), st;
for (int v = 0; v < (int)size(); v++) for (const auto &e : list[v]) deg[e.to] += (e.cap > 0);
st.reserve(size());
for (int v = 0; v < (int)size(); v++) if (!deg[v]) st.emplace_back(v);
for (int i = 0; i < (int)size(); i++) {
if ((int)st.size() == i) return false; // not DAG
int cur = st[i];
for (const auto &e : list[cur]) {
if (e.cap <= 0) continue;
deg[e.to]--;
if (deg[e.to] == 0) st.emplace_back(e.to);
if (pot[e.to] >= pot[cur] + e.cost) pot[e.to] = pot[cur] + e.cost;
}
}
return true;
}
bool calc_potential_spfa() {
pot.assign(size(), 0);
queue<int> que;
vector<bool> inque(size(), false);
vector<int> cnt(size(), 0);
for (int v = 0; v < (int)size(); v++) que.push(v), inque[v] = true;
while (!que.empty()) {
int cur = que.front();
que.pop();
inque[cur] = false;
if (cnt[cur] > (int)size()) return false; // include negative-cycle
cnt[cur]++;
for (const auto &e : list[cur]) {
if (e.cap <= 0) continue;
if (pot[e.to] > pot[cur] + e.cost) {
pot[e.to] = pot[cur] + e.cost;
if (!inque[e.to]) inque[e.to] = true, que.push(e.to);
}
}
}
return true;
}
bool calc_potential() {
return calc_potential_dag() || calc_potential_spfa();
}
bool init_potential() {
if (!include_negative_edge) return true;
return calc_potential();
}
// decompose flow into s-t simple paths and cycles
using Path = vector<FlowCostEdge<FLOW, COST>>;
pair<vector<Path>, vector<Path>> decompose(int s, int t) const {
struct Arc {
int to;
FLOW rem;
int eidx;
};
vector<vector<Arc>> fg(list.size());
for (int v = 0; v < (int)list.size(); v++) {
for (int j = 0; j < (int)list[v].size(); j++) {
FLOW f = list[v][j].icap - list[v][j].cap;
if (f > 0) fg[v].push_back({list[v][j].to, f, j});
}
}
vector<Path> paths, cycles;
auto build = [&](const vector<pair<int,int>> &route, bool is_cycle) {
FLOW mi = numeric_limits<FLOW>::max();
for (auto [v,i] : route) mi = min(mi, fg[v][i].rem);
vector<FlowCostEdge<FLOW,COST>> seq;
for (auto [v,i] : route) {
fg[v][i].rem -= mi;
FlowCostEdge<FLOW,COST> e = list[v][fg[v][i].eidx];
e.flow = mi;
seq.push_back(e);
}
if (is_cycle) cycles.push_back(std::move(seq));
else paths.push_back(std::move(seq));
};
// Phase 1: extract all cycles and make graph DAG
const int NOTSEEN = 0, INSTACK = 1, FINISH = 2;
vector<int> color(list.size(), NOTSEEN);
vector<int> pos_in_stack(list.size(), -1);
vector<pair<int, int>> stk;
auto dfs = [&](auto &&dfs, int v) -> bool {
color[v] = INSTACK;
pos_in_stack[v] = (int)stk.size();
for (int i = 0; i < (int)fg[v].size(); i++) {
if (fg[v][i].rem <= 0) continue;
int u = fg[v][i].to;
if (color[u] == INSTACK) {
vector<pair<int,int>> route;
for (int k = pos_in_stack[u]; k < (int)stk.size(); k++) {
route.push_back(stk[k]);
}
route.push_back({v, i});
build(route, true);
return true;
}
if (color[u] == NOTSEEN) {
stk.push_back({v, i});
if (dfs(dfs, u)) return true;
stk.pop_back();
}
}
color[v] = FINISH;
pos_in_stack[v] = -1;
return false;
};
while (true) {
fill(color.begin(), color.end(), NOTSEEN);
stk.clear();
bool found = false;
for (int v = 0; v < (int)list.size() && !found; v++) {
if (color[v] == NOTSEEN && dfs(dfs, v)) found = true;
}
if (!found) break;
}
// Phase 2: find all s-t paths
vector<int> ptr(list.size(), 0);
auto next_arc = [&](int v) -> int {
while (ptr[v] < (int)fg[v].size() && fg[v][ptr[v]].rem <= 0) ptr[v]++;
return ptr[v] < (int)fg[v].size() ? ptr[v] : -1;
};
while (next_arc(s) != -1) {
vector<pair<int,int>> route;
int v = s;
while (v != t) {
int i = next_arc(v);
route.push_back({v, i});
v = fg[v][i].to;
}
build(route, false);
}
return {paths, cycles};
}
// debug
friend ostream& operator << (ostream& s, const FlowCostGraph &G) {
const auto &edges = G.get_edges();
for (const auto &e : edges) s << e << endl;
return s;
}
};
// Min Cost Circulation Flow by Cost-Scaling
template<class FLOW, class COST> COST MinCostCirculation(FlowCostGraph<FLOW, COST> &G) {
COST eps = 0;
vector<FLOW> balance(G.size(), 0);
vector<COST> price(G.size(), 0);
auto newcost = [&](const FlowCostEdge<FLOW, COST> &e) -> COST {
return e.cost * (COST)G.size() - price[e.from] + price[e.to];
};
auto ConstructGaux = [&]() -> void {
vector<bool> visited(G.size(), false);
auto dfs = [&](auto &&dfs, int v) -> void {
visited[v] = true;
for (int i = 0; i < G[v].size(); ++i) {
FlowCostEdge<FLOW, COST> &e = G[v][i];
if (e.cap > 0 && !visited[e.to] && newcost(e) < 0) dfs(dfs, e.to);
}
};
for (int v = 0; v < G.size(); ++v) if (balance[v] > 0) dfs(dfs, v);
for (int v = 0; v < G.size(); ++v) if (visited[v]) price[v] += eps;
};
auto augment_blocking_flow = [&]() -> bool {
vector<int> iter(G.size(), 0);
auto augment = [&](auto &&augment, int v, FLOW flow) -> FLOW {
if (balance[v] < 0) {
FLOW dif = min(flow, -balance[v]);
balance[v] += dif;
return dif;
}
for (; iter[v] < G[v].size(); iter[v]++) {
auto &e = G[v][iter[v]], &re = G.get_rev_edge(e);
if (e.cap > 0 && newcost(e) < 0) {
FLOW dif = augment(augment, e.to, min(flow, e.cap));
if (dif > 0) {
e.cap -= dif, e.flow += dif;
re.cap += dif, re.flow -= dif;
return dif;
}
}
}
return 0;
};
bool finish = true;
for (int v = 0; v < G.size(); ++v) {
FLOW flow;
while (balance[v] > 0 && (flow = augment(augment, v, balance[v])) > 0)
balance[v] -= flow;
if (balance[v] > 0) finish = false;
}
if (finish) return true;
else return false;
};
for (int v = 0; v < G.size(); ++v) {
for (int i = 0; i < G[v].size(); ++i) {
FlowCostEdge<FLOW, COST> &e = G[v][i];
if (e.cap > 0) eps = max(eps, -e.cost * (COST)G.size());
}
price[v] = 0;
}
while (eps > 1) {
eps /= 2;
for (int v = 0; v < G.size(); ++v) {
for (int i = 0; i < G[v].size(); ++i) {
auto &e = G[v][i], &re = G.get_rev_edge(e);
if (e.cap > 0 && newcost(e) < 0) {
FLOW flow = e.cap;
balance[e.from] -= flow, balance[e.to] += flow;
e.cap -= flow, e.flow += flow;
re.cap += flow, re.flow -= flow;
}
}
}
while (true) {
ConstructGaux();
if (augment_blocking_flow()) break;
}
}
COST res = 0;
const auto &edges = G.get_edges();
for (const auto &e : edges) res += e.flow * e.cost;
return res;
}
//------------------------------//
// Examples
//------------------------------//
// AOJ Course GRL_6_B Network Flow - Minimum Cost Flow
void AOJ_Course_GRL_6_B() {
const long long INF = 1<<29; // 十分大きい値
// 入力
int V, E;
long long F;
cin >> V >> E >> F;
FlowCostGraph<long long, long long> G(V);
for (int i = 0; i < E; ++i) {
int u, v, cap, cost;
cin >> u >> v >> cap >> cost;
G.add_edge(u, v, cap, cost);
}
// 流量 F を強制するために、t から s へコスト -INF の辺を張る
int s = 0, t = V-1;
G.add_edge(t, s, F, -INF);
// 最小費用循環流
long long res = MinCostCirculation(G) + F * INF;
// 流量 F を流せない場合
if (res >= INF) cout << -1 << endl;
else cout << res << endl;
}
int main() {
AOJ_Course_GRL_6_B();
}