Pagini recente » Cod sursa (job #1909280) | Cod sursa (job #1782494) | Cod sursa (job #2977576) | Cod sursa (job #2602029) | Cod sursa (job #2961351)
#include <bits/stdc++.h>
using namespace std;
ifstream f("maxflow.in");
ofstream g("maxflow.out");
#define cin f
#define cout g
const int Max = 1e3 + 1;
// the matrix capacity stores the residual network capacity
int n, m, capacity[Max][Max];
vector<int> adj[Max];
int bfs(int s, int t, vector<int> &parent)
{
fill(parent.begin(), parent.end(), -1);
parent[s] = -2;
queue<pair<int, int>> Q;
Q.push({s, INT_MAX});
while(! Q.empty())
{
int cur = Q.front().first;
int flow = Q.front().second;
Q.pop();
for(int next : adj[cur])
{
if(parent[next] == -1 and capacity[cur][next] != 0)
{
parent[next] = cur;
int new_flow = min(flow, capacity[cur][next]);
if(next == t)
return new_flow;
Q.push({next, new_flow});
}
}
}
return 0;
}
int maxflow(int s, int t)
{
int flow = 0, new_flow;
vector<int> parent(n + 1);
while(new_flow = bfs(s, t, parent))
{
flow += new_flow;
int cur = t;
while(cur != s)
{
int prev = parent[cur];
capacity[cur][prev] += new_flow;
capacity[prev][cur] -= new_flow;
cur = prev;
}
}
return flow;
}
int main()
{
cin >> n >> m;
for(int i = 1; i <= m; i ++)
{
int x, y, c;
cin >> x >> y >> c;
adj[x].push_back(y);
adj[y].push_back(y);
capacity[x][y] = c;
}
cout<<maxflow(1, n)<<'\n';
return 0;
}