-
Notifications
You must be signed in to change notification settings - Fork 2
/
Dinic.cpp
140 lines (109 loc) · 2.4 KB
/
Dinic.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
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
struct Edge
{
int end;
i64 capa, flow;
Edge* dual;
Edge() : Edge(-1, 0) {}
Edge(int e, i64 c) : end(e), capa(c), flow(0), dual(nullptr) {}
i64 remain()
{
return capa - flow;
}
void add_flow(i64 f)
{
flow += f;
dual->flow -= f;
}
};
template<int Size>
class Dinic
{
public:
const i64 INFINITE = 1ll << 62;
~Dinic()
{
for (auto& a : adj)
{
for (auto& e : a)
{
delete e;
}
}
}
Edge* add_edge(int a, int b, i64 c)
{
auto e1 = new Edge(b, c);
auto e2 = new Edge(a, 0);
e1->dual = e2;
e2->dual = e1;
adj[a].push_back(e1);
adj[b].push_back(e2);
return e1;
}
i64 max_flow(int source, int sink)
{
i64 totalFlow = 0;
while (bfs(source, sink))
{
memset(work, 0, sizeof(work));
while (true)
{
i64 flow = dfs(source, sink, INFINITE);
if (flow == 0)
break;
totalFlow += flow;
}
}
return totalFlow;
}
int edge_count(int s)
{
return adj[s].size();
}
Edge* get_edge(int s, int i)
{
return adj[s][i];
}
private:
vector<Edge*> adj[Size];
int level[Size];
int work[Size];
bool bfs(int source, int sink)
{
memset(level, -1, sizeof(level));
level[source] = 0;
queue<int> q;
q.push(source);
while (!q.empty())
{
int now = q.front();
q.pop();
for (auto& e : adj[now])
{
if (level[e->end] != -1 || e->remain() <= 0)
continue;
level[e->end] = level[now] + 1;
q.push(e->end);
}
}
return level[sink] != -1;
}
i64 dfs(int s, int e, i64 f)
{
if (s == e)
return f;
for (int& i = work[s]; i < adj[s].size(); i++)
{
auto& next = adj[s][i];
if (level[next->end] != level[s] + 1 || next->remain() <= 0)
continue;
i64 df = dfs(next->end, e, min(f, next->remain()));
if (df != 0)
{
next->add_flow(df);
return df;
}
}
return 0;
}
};