-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathMCMF.cpp
85 lines (73 loc) · 1.94 KB
/
MCMF.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
76
77
78
79
80
81
82
83
84
85
template<int V>
class MCMF
{
public:
int capa[V][V];
int cost[V][V];
int flow[V][V];
vector<int> adj[V];
int prev[V], dist[V];
bool inQ[V];
void add_edge(int u, int v, int ecapa, int ecost)
{
capa[u][v] = ecapa;
cost[u][v] = ecost;
cost[v][u] = -ecost;
adj[u].push_back(v);
adj[v].push_back(u);
}
ii mcmf(int start, int end)
{
int min_cost = 0;
int max_flow = 0;
while (true)
{
spfa(start, end);
if (prev[end] == -1)
break;
int now_flow = INF;
for (int i = end; i != start; i = prev[i])
now_flow = min(now_flow, capa[prev[i]][i] - flow[prev[i]][i]);
for (int i = end; i != start; i = prev[i])
{
min_cost += now_flow * cost[prev[i]][i];
flow[prev[i]][i] += now_flow;
flow[i][prev[i]] -= now_flow;
}
max_flow += now_flow;
}
return ii(min_cost, max_flow);
}
void spfa(int start, int end)
{
queue<int> q;
fill(inQ, inQ + V, false);
fill(prev, prev + V, -1);
fill(dist, dist + V, INF);
dist[start] = 0;
inQ[start] = true;
q.push(start);
while (!q.empty())
{
int now = q.front();
q.pop();
inQ[now] = false;
for (auto& next : adj[now])
{
if (capa[now][next] - flow[now][next] > 0 &&
dist[next] > dist[now] + cost[now][next])
{
dist[next] = dist[now] + cost[now][next];
prev[next] = now;
if (!inQ[next])
{
q.push(next);
inQ[next] = true;
}
}
}
}
}
private:
const int INF = 1 << 30;
};