-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcses_1694.cpp
More file actions
105 lines (101 loc) · 2.34 KB
/
cses_1694.cpp
File metadata and controls
105 lines (101 loc) · 2.34 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
#include <bits/extc++.h>
using namespace std;
typedef long long ll;
template <typename T>
struct DINIC
{
static const int MAXN = 1087;
static const T INF = INT_MAX;
int n, LV[MAXN], cur[MAXN];
struct edge
{
int v, pre;
T cap, r;
edge(int v, int pre, T cap) : v(v), pre(pre), cap(cap), r(cap) {}
};
int g[MAXN];
vector<edge> e;
void init(int _n)
{
memset(g, -1, sizeof(int) * ((n = _n) + 1));
e.clear();
}
void add_edge(int u, int v, T cap, bool directed = false)
{
e.push_back(edge(v, g[u], cap));
g[u] = e.size() - 1;
e.push_back(edge(u, g[v], directed ? 0 : cap));
g[v] = e.size() - 1;
}
int bfs(int s, int t)
{
memset(LV, 0, sizeof(int) * (n + 1));
memcpy(cur, g, sizeof(int) * (n + 1));
queue<int> q;
q.push(s);
LV[s] = 1;
while (q.size())
{
int u = q.front();
q.pop();
for (int i = g[u]; ~i; i = e[i].pre)
{
if (!LV[e[i].v] && e[i].r)
{
LV[e[i].v] = LV[u] + 1;
q.push(e[i].v);
if (e[i].v == t)
return 1;
}
}
}
return 0;
}
T dfs(int u, int t, T CF = INF)
{
if (u == t)
return CF;
T df;
for (int &i = cur[u]; ~i; i = e[i].pre)
{
if (LV[e[i].v] == LV[u] + 1 && e[i].r)
{
if (df = dfs(e[i].v, t, min(CF, e[i].r)))
{
e[i].r -= df;
e[i ^ 1].r += df;
return df;
}
}
}
return LV[u] = 0;
}
T dinic(int s, int t, bool clean = true)
{
if (clean)
for (size_t i = 0; i < e.size(); ++i)
e[i].r = e[i].cap;
T ans = 0, f = 0;
while (bfs(s, t))
while (f = dfs(s, t))
ans += f;
return ans;
}
};
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
int n, m;
DINIC<ll> d;
cin >> n >> m;
d.init(n);
while (m--)
{
ll u, v, w;
cin >> u >> v >> w;
d.add_edge(u, v, w, true);
}
cout << d.dinic(1, n) << '\n';
return 0;
}