-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathmin_cost_flow_primal_dual.cpp
More file actions
304 lines (268 loc) · 10.2 KB
/
Copy pathmin_cost_flow_primal_dual.cpp
File metadata and controls
304 lines (268 loc) · 10.2 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
//
// min-cost flow (primal-dual)
//
// verified
// 典型アルゴリズム問題集 上級〜エキスパート編 F - 最小費用流
// https://atcoder.jp/contests/pastbook2022/tasks/pastbook2022_f
//
// AtCoder Library Practice Contest E - MinCostFlow
// https://atcoder.jp/contests/practice2/tasks/practice2_e
//
#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 < list.size());
return list[i];
}
const vector<FlowCostEdge<FLOW, COST>> &operator [] (int i) const {
assert(0 <= i && i < list.size());
return list[i];
}
size_t size() const {
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 < list.size() && 0 <= to && to < 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 < list.size() && 0 <= to && to < 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 < list.size() && 0 <= to && to < list.size());
assert(cap >= 0);
add_edge(from, to, cap, cap, cost);
}
// 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 max-flow (<= limit_flow), slope ver.
template<class FLOWTYPE, class COSTTYPE> vector<pair<FLOWTYPE, COSTTYPE>>
MinCostFlowSlope(FlowCostGraph<FLOWTYPE, COSTTYPE> &G, int S, int T, FLOWTYPE limit_flow)
{
// result values
FLOWTYPE cur_flow = 0;
COSTTYPE cur_cost = 0, pre_cost = -1;
vector<pair<FLOWTYPE, COSTTYPE>> res;
res.emplace_back(cur_flow, cur_cost);
// intermediate values
vector<COSTTYPE> dual((int)G.size(), 0), dist((int)G.size());
vector<int> prevv((int)G.size(), -1), preve((int)G.size(), -1);
// dual
auto dual_step = [&]() -> bool {
priority_queue<pair<COSTTYPE,int>, vector<pair<COSTTYPE,int>>, greater<pair<COSTTYPE,int>>> que;
que.push({0, S});
dist.assign((int)G.size(), numeric_limits<COSTTYPE>::max());
dist[S] = 0;
while (!que.empty()) {
auto [cur_cost, v] = que.top();
que.pop();
if (dist[v] < cur_cost) continue;
for (int i = 0; i < (int)G[v].size(); ++i) {
const auto &e = G[v][i];
COSTTYPE new_cost = e.cost + dual[v] - dual[e.to];
if (e.cap > 0 && dist[e.to] > dist[v] + new_cost) {
dist[e.to] = dist[v] + new_cost;
prevv[e.to] = v;
preve[e.to] = i;
que.push({dist[e.to], e.to});
}
}
}
if (dist[T] == numeric_limits<COSTTYPE>::max()) return false;
for (int v = 0; v < (int)G.size(); ++v) {
if (dist[T] == numeric_limits<COSTTYPE>::max()) continue;
dual[v] -= dist[T] - dist[v];
}
return true;
};
// primal
auto primal_step = [&]() -> void {
FLOWTYPE flow = limit_flow - cur_flow;
COSTTYPE cost = -dual[S];
for (int v = T; v != S; v = prevv[v]) {
flow = min(flow, G[prevv[v]][preve[v]].cap);
}
for (int v = T; v != S; v = prevv[v]) {
FlowCostEdge<FLOWTYPE, COSTTYPE> &e = G[prevv[v]][preve[v]];
FlowCostEdge<FLOWTYPE, COSTTYPE> &re = G.get_rev_edge(e);
e.cap -= flow, e.flow += flow;
re.cap += flow, re.flow -= flow;
}
cur_flow += flow;
cur_cost += flow * cost;
if (pre_cost == cost) res.pop_back();
res.emplace_back(cur_flow, cur_cost);
pre_cost = cur_cost;
};
// primal-dual
while (cur_flow < limit_flow) {
if (!dual_step()) break;
primal_step();
}
return res;
}
// min-cost max-flow, slope ver.
template<class FLOWTYPE, class COSTTYPE> vector<pair<FLOWTYPE, COSTTYPE>>
MinCostFlowSlope(FlowCostGraph<FLOWTYPE, COSTTYPE> &G, int S, int T)
{
return MinCostFlowSlope(G, S, T, numeric_limits<FLOWTYPE>::max());
}
// min-cost max-flow (<= limit_flow)
template<class FLOWTYPE, class COSTTYPE> pair<FLOWTYPE, COSTTYPE>
MinCostFlow(FlowCostGraph<FLOWTYPE, COSTTYPE> &G, int S, int T, FLOWTYPE limit_flow)
{
return MinCostFlowSlope(G, S, T, limit_flow).back();
}
// min-cost max-flow (<= limit_flow)
template<class FLOWTYPE, class COSTTYPE> pair<FLOWTYPE, COSTTYPE>
MinCostFlow(FlowCostGraph<FLOWTYPE, COSTTYPE> &G, int S, int T)
{
return MinCostFlow(G, S, T, numeric_limits<FLOWTYPE>::max());
}
//------------------------------//
// Examples
//------------------------------//
// 典型アルゴリズム問題集 上級〜エキスパート編 F - 最小費用流
void PAST_Min_Cost_Flow() {
long long V, E, F;
cin >> V >> E >> F;
FlowCostGraph<long long, long long> G(V);
for (int i = 0; i < E; ++i) {
long long u, v, cap, cost;
cin >> u >> v >> cap >> cost, u--, v--;
G.add_edge(u, v, cap, cost);
}
long long s = 0, t = V-1;
auto [max_flow, min_cost] = MinCostFlow(G, s, t, F);
cout << (max_flow == F ? min_cost : -1) << endl;
}
// ACL practice E
void ACL_practice_E() {
// 十分大きな値
const long long B = 1LL<<40;
// 入力
int N, K;
cin >> N >> K;
vector<vector<long long>> A(N, vector<long long>(N));
for (int i = 0; i < N; ++i) for (int j = 0; j < N; ++j) cin >> A[i][j];
// フローネットワークを作る
// 行番号に対応する頂点を 0, 1, ..., N-1、列番号に対応する頂点を N, N+1, ..., 2N-1 とする
// 超頂点の番号を S = 2N, T = 2N+1 とする
FlowCostGraph<int, long long> G(N * 2 + 2);
int S = N * 2, T = N * 2 + 1;
// 行と列を結ぶ
for (int i = 0; i < N; ++i) {
for (int j = 0; j < N; ++j) {
// 容量 1、コスト B - A[i][j]
G.add_edge(i, j + N, 1, B - A[i][j]);
}
}
// 超頂点
for (int i = 0; i < N; ++i) {
G.add_edge(S, i, K, 0); // 容量 K, コスト 0
G.add_edge(i + N, T, K, 0); // 容量 K, コスト 0
}
// バイパス
G.add_edge(S, T, N * K, B);
// 流量 N * K の最小費用流を流す (最大流量も受け取るが N * K になることは分かっている)
auto [max_flow, min_cost] = MinCostFlow(G, S, T, N * K);
// 復元する
vector<string> grid(N, string(N, '.'));
const auto &edges = G.get_edges();
for (const auto &e : edges) {
// 超頂点が絡む辺や、フローの流れなかった辺はスキップ
if (e.from == S || e.to == T || e.flow == 0) continue;
// 行 e.from、列 e.to - N が選ばれる
grid[e.from][e.to - N] = 'X';
}
// 出力
cout << B * N * K - min_cost << endl;
for (int i = 0; i < N; ++i) cout << grid[i] << endl;
}
int main() {
PAST_Min_Cost_Flow();
//ACL_practice_E();
}