Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 5570279

Browse files
Dinic's algorithm
1 parent 7a80b36 commit 5570279

File tree

1 file changed

+95
-0
lines changed

1 file changed

+95
-0
lines changed

‎dinic.cpp

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
#include <bits/stdc++.h>
2+
#define ll long long
3+
#define INF 1000000000000007
4+
using namespace std;
5+
6+
const ll nodes = 1002;
7+
vector<vector<ll>> adj(nodes);
8+
vector<vector<ll>> capacity(nodes, vector<ll>(nodes)), flow(nodes, vector<ll>(nodes));
9+
vector<ll> dist, pt;
10+
queue<ll> q;
11+
ll src, dest;
12+
13+
void add_edge(ll u, ll v, ll c) {
14+
if (u != v) {
15+
adj[u].push_back(v);
16+
adj[v].push_back(u);
17+
capacity[u][v] += c;
18+
capacity[v][u] += c;
19+
}
20+
}
21+
22+
bool bfs(ll lim) {
23+
fill(dist.begin(), dist.end(),INF);
24+
dist[src] = 0;
25+
q.push(src);
26+
27+
while (!q.empty() and dist[dest] == INF) {
28+
ll u = q.front(); q.pop();
29+
30+
for (ll to : adj[u]) {
31+
if (dist[to] == INF and capacity[u][to] - flow[u][to] >= lim) {
32+
dist[to] = dist[u] + 1;
33+
q.push(to);
34+
}
35+
}
36+
}
37+
while (!q.empty()) q.pop();
38+
39+
return dist[dest] != INF;
40+
}
41+
42+
bool dfs(ll u, ll curr_flow) {
43+
if (curr_flow == 0 or u == dest) {
44+
return curr_flow;
45+
}
46+
47+
for (; pt[u] < adj[u].size(); pt[u]++) {
48+
ll to = adj[u][pt[u]];
49+
50+
if (dist[to] == dist[u] + 1 and capacity[u][to] - flow[u][to] >= curr_flow) {
51+
bool pushed = dfs(to, curr_flow);
52+
if (pushed) {
53+
flow[u][to] += curr_flow;
54+
flow[to][u] -= curr_flow;
55+
return true;
56+
}
57+
}
58+
}
59+
60+
return false;
61+
}
62+
63+
ll dinic() {
64+
ll flow = 0, lim = (1 << 30);
65+
while (lim >= 1) {
66+
if (!bfs(lim)) {
67+
lim >>= 1;
68+
continue;
69+
}
70+
fill(pt.begin(), pt.end(),0);
71+
72+
while (dfs(src, lim)) {
73+
flow += lim;
74+
}
75+
}
76+
return flow;
77+
}
78+
79+
int main() {
80+
ll n,m,i,u,v,c;
81+
cin >> n >> m;
82+
adj.resize(n);
83+
dist.resize(n);
84+
pt.resize(n);
85+
86+
for (i = 0; i < m; i++) {
87+
cin >> u >> v >> c;
88+
u--;v--;
89+
add_edge(u,v,c);
90+
}
91+
cin >> src >> dest;
92+
src--;dest--;
93+
cout << dinic() << endl;
94+
return 0;
95+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /