-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdinic.sublime-snippet
126 lines (83 loc) · 1.92 KB
/
dinic.sublime-snippet
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
<snippet>
<content><![CDATA[
struct Dinic
{
const ll DINF = 1e18;
int n, source, sink;
vector<ll> dist;
vector<vector<int>> g;
vector<int> o;
vector<pair<int,ll>> e;
Dinic(int _n, int S = -1, int T = -1) {
if (S == -1) S = 0;
if (T == -1) T = n - 1;
n = _n;
source = S;
sink = T;
dist = vector<ll>(n, DINF);
g = vector<vector<int>>(n);
}
int bfs() {
for (int i = 0; i < n; i++)
dist[i] = DINF;
queue<ll> curr;
curr.push(source);
dist[source] = 0;
while (curr.size()) {
int c = curr.front();
curr.pop();
for (int i : g[c]) {
int ei = e[i].first;
if (dist[ei] > dist[c] + 1 && e[i].second > 0) {
dist[ei] = dist[c] + 1;
curr.push(ei);
}
}
}
return (dist[sink] < DINF);
}
void add(int x, int y, ll cap) {
int s = e.size();
o.push_back(s + 1);
o.push_back(s);
g[x].push_back(s++);
g[y].push_back(s++);
e.push_back({y, cap});
e.push_back({x, 0});
}
void add_flow(int ei, ll v) {
e[ ei ].second -= v;
e[o[ei]].second += v;
}
ll send_flow(int c, ll cap) {
if (c == sink || cap == 0) return cap;
ll tot = 0, rem = cap;
for (int i : g[c]) {
int ni = e[i].first;
if (dist[ni] != dist[c] + 1)
continue;
ll ts = min(rem, e[i].second);
ll sent = send_flow(ni, ts);
add_flow(i, sent);
tot += sent;
rem -= sent;
if (!rem) break;
}
if (tot == 0) dist[c] = DINF;
return tot;
}
ll solve() {
ll ans = 0;
while (bfs()) {
ll fs = send_flow(source, DINF);
ans += fs;
}
return ans;
}
};
]]></content>
<!-- Optional: Set a tabTrigger to define how to trigger the snippet -->
<tabTrigger>dinic</tabTrigger>
<!-- Optional: Set a scope to limit where the snippet will trigger -->
<!-- <scope>source.python</scope> -->
</snippet>