forked from spectre900/Binary-Image-Segmentation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dinic.cpp
97 lines (84 loc) · 1.88 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
#include <bits/stdc++.h>
#include "graph.h"
using namespace std;
class Dinic : public Graph
{
vector<int> level;
public:
int dfs(int u, int flow = INT_MAX)
{
if (u == sink)
{
return flow;
}
done[u] = true;
for (pair<int, int> edge : adjList[u])
{
int v = edge.first;
int w = edge.second;
if (w and level[v] == level[u] + 1)
{
int curFlow = dfs(v, min(flow, w));
if (curFlow)
{
adjList[u][v] -= curFlow;
adjList[v][u] += curFlow;
return curFlow;
}
}
}
return 0;
}
int bfs()
{
level = vector<int>(V, -1);
queue<int> q;
q.push(source);
level[source] = 0;
while (!q.empty())
{
int u = q.front();
q.pop();
for (pair<int, int> edge : adjList[u])
{
int v = edge.first;
int w = edge.second;
if (w and level[v] == -1)
{
q.push(v);
level[v] = level[u] + 1;
}
}
}
return level[sink] != -1;
}
int findMaxFlow()
{
while (bfs())
{
while (true)
{
int flow = dfs(source);
if (flow)
{
maxFlow += flow;
continue;
}
break;
}
}
return maxFlow;
}
};
int main()
{
Dinic d = Dinic();
d.readInput();
clock_t start, end;
start = clock();
d.findMaxFlow();
d.findForeGround();
end = clock();
double duration = double(end - start) / double(CLOCKS_PER_SEC);
cout << duration;
}