Pagini recente » Cod sursa (job #3290986) | Cod sursa (job #3285649)
#include <bits/stdc++.h>
#pragma GCC optimize("O3", "Ofast", "unroll-loops")
using namespace std;
using ll = long long;
// #define int ll
using pii = pair<int, int>;
const int MOD = 1e9 + 7;
const int INF = 1e9;
const int dx[4] = {-1, 1, 0, 0}, dy[4] = {0, 0, -1, 1}; // N S E V
const int MAXN = 2e5 + 5;
int n, m;
struct Dinic
{
struct Edge
{
int u, v;
int c;
};
vector<Edge> e;
vector<vector<int>> adj;
vector<int> d;
void init()
{
adj.resize(n + 1);
}
void add_edge(int u, int v, int c)
{
adj[u].push_back(e.size());
e.push_back({u, v, c});
adj[v].push_back(e.size());
e.push_back({v, u, 0});
}
bool bfs(int s, int t)
{
d.assign(n + 1, INF);
d[s] = 0;
queue<int> q;
q.push(s);
while(!q.empty())
{
int u = q.front();
q.pop();
for(int y : adj[u])
{
if(e[y].c && d[e[y].v] == INF)
{
d[e[y].v] = d[u] + 1;
q.push(e[y].v);
}
}
}
return d[t] != INF;
}
int dfs(int s, int t, int flow)
{
if(s == t)
return flow;
for(int y : adj[s])
{
if(e[y].c && d[e[y].v] == d[s] + 1)
{
int newflow = dfs(e[y].v, t, min(e[y].c, flow));
if(newflow)
{
e[y].c -= newflow;
e[y ^ 1].c += newflow;
}
return newflow;
}
}
return 0;
}
int maxflow(int s, int t)
{
int ans = 0;
while(bfs(s, t))
{
ans += dfs(s, t, INF);
}
return ans;
}
};
Dinic mf;
int32_t main()
{
#ifndef LOCAL
ifstream cin("maxflow.in");
ofstream cout("maxflow.out");
#endif
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cin >> n >> m;
mf.init();
for(int i = 1; i <= m; i++)
{
int u, v, c;
cin >> u >> v >> c;
mf.add_edge(u, v, c);
}
cout << mf.maxflow(1, n);
return 0;
}