Pagini recente » Cod sursa (job #2852887) | Cod sursa (job #2169299) | Cod sursa (job #2644853) | Cod sursa (job #2396347) | Cod sursa (job #2899918)
#include <iostream>
#include <vector>
#include <queue>
#define s second
#define f first
using namespace std;
typedef long long ll;
int n, m;
pair<ll , ll> flux[1005][1004];
vector<vector<int>> adj;
bool viz[1001];
int par[1001];
int bfs ()
{
queue<int> q;
q.push(1);
viz[1] = true;
bool found = 0;
while (!q.empty())
{
int crt = q.front();
q.pop();
viz[crt] = true;
if (crt == n){
found = 1;
break;
}
else {
for (auto to : adj[crt])
{
if (!viz[to] && flux[crt][to].s - flux[crt][to].f > 0)
{
par[to] = crt;
q.push(to);
}
}
}
}
if (found){
ll minflow = 1e9;
for (int nod = n; nod != 1; nod = par[nod])
{
minflow = min(minflow, flux[par[nod]][nod].s - flux[par[nod]][nod].f);
}
for (int nod = n; nod != 1; nod = par[nod])
{
flux[par[nod]][nod].f += minflow;
flux[nod][par[nod]].f -= minflow;
}
for (int i = 1; i <= n; i++)
{
viz[i] = 0;
par[i] = 0;
}
return minflow;
}
else return 0;
}
int main ()
{
freopen("maxflow.in", "r", stdin);
freopen("maxflow.out", "w", stdout);
cin >> n >> m;
adj.resize(n + 1);
for (int i = 1; i <= m; i++)
{
int x, y; ll fx; cin >> x >> y >> fx;
adj[x].push_back(y);
adj[y].push_back(x);
flux[x][y] = {0, fx};
flux[y][x] = {0, 0};
}
ll bottleneck = 0;
ll ans = 0;
do {
bottleneck = bfs();
ans += bottleneck;
} while (bottleneck != 0);
cout << ans << '\n';
}