Pagini recente » Cod sursa (job #2575192) | Cod sursa (job #1679876) | Cod sursa (job #1322925) | Cod sursa (job #1273288) | Cod sursa (job #2951485)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
struct edge
{
int a;
int b;
int cap;
int flow;
};
struct Dinic
{
vector<edge> edges;
vector<int> level;
vector<int> next;
vector<vector<int>> g;
int s, t;
void init(int _n, int _s, int _t)
{
s = _s;
t = _t;
level = next = vector<int>(_n + 1);
g = vector<vector<int>>(_n + 1);
}
void add_edge(int a, int b, int cap)
{
int m = (int)edges.size();
edges.push_back({a, b, cap, 0});
edges.push_back({b, a, 0, 0});
g[a].push_back(m);
g[b].push_back(m + 1);
}
bool bfs()
{
queue<int> q;
q.push(s);
level[s] = 0;
while (!q.empty())
{
int qui = q.front();
q.pop();
for (auto i : g[qui])
{
edge x = edges[i];
if (x.cap - x.flow < 1 || level[x.b] != -1)
{
continue;
}
level[x.b] = level[qui] + 1;
q.push(x.b);
}
}
return level[t] != -1;
}
int dfs(int node, int push)
{
if (node == t || push == 0)
{
return push;
}
for (int &i = next[node]; i < (int)g[node].size(); ++i)
{
edge x = edges[g[node][i]];
if (x.cap - x.flow < 1 || level[x.b] != level[node] + 1)
{
continue;
}
int flow = dfs(x.b, min(push, x.cap - x.flow));
if (flow == 0)
{
continue;
}
edges[g[node][i]].flow += flow;
edges[g[node][i] ^ 1].flow -= flow;
return flow;
}
return 0;
}
int flow()
{
int ans = 0;
while (true)
{
fill(level.begin(), level.end(), -1);
fill(next.begin(), next.end(), 0);
if (!bfs())
{
break;
}
while (int add = dfs(s, INT_MAX))
{
ans += add;
}
}
return ans;
}
};
int main()
{
cin.tie(nullptr)->sync_with_stdio(false);
int n, m;
fin >> n >> m;
Dinic G;
G.init(n, 1, n);
for (int i = 1; i <= m; ++i)
{
int a, b, cost;
fin >> a >> b >> cost;
G.add_edge(a, b, cost);
}
fout << G.flow();
}