Pagini recente » Cod sursa (job #2726763) | Cod sursa (job #1856723) | Cod sursa (job #615135) | Cod sursa (job #2731722) | Cod sursa (job #2496832)
#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;
const int N = 1000 + 7;
int n;
int m;
int cap[N][N];
vector<int> g[N];
bool u[N];
int p[N];
bool BFS()
{
u[1] = 1;
for (int i = 2; i <= n; i++)
{
u[i] = 0;
}
queue<int> q;
q.push(1);
while (!q.empty())
{
int a = q.front();
q.pop();
for (auto &b : g[a])
{
if (cap[a][b] > 0 && u[b] == 0)
{
p[b] = a;
u[b] = 1;
q.push(b);
}
}
}
return u[n];
}
int main()
{
freopen ("maxflow.in", "r", stdin);
freopen ("maxflow.out", "w", stdout);
cin >> n >> m;
for (int i = 1; i <= m; i++)
{
int a, b, c;
cin >> a >> b >> c;
cap[a][b] += c;
g[a].push_back(b);
g[b].push_back(a);
}
int ans = 0;
while (BFS())
{
for (auto &a : g[n])
{
if (cap[a][n] > 0)
{
vector<int> kek = {n, a};
int b = p[a];
while (b)
{
kek.push_back(b);
b = p[b];
}
reverse(kek.begin(), kek.end());
int mn = (1 << 30);
for (int j = 0; j + 1 < (int) kek.size(); j++)
{
mn = min(mn, cap[kek[j]][kek[j + 1]]);
}
if (mn)
{
ans += mn;
for (int j = 0; j + 1 < (int) kek.size(); j++)
{
int a = kek[j];
int b = kek[j + 1];
cap[a][b] -= mn;
cap[b][a] += mn;
}
}
}
}
}
cout << ans << "\n";
}