Pagini recente » Cod sursa (job #2388043) | Cod sursa (job #3318062) | Cod sursa (job #69768) | Cod sursa (job #1161766) | Cod sursa (job #3336307)
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
using namespace std;
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
const int NMAX = 1005;
const int INF = 1e9;
vector<int> G[NMAX];
int capacity[NMAX][NMAX];
int parent[NMAX];
int N, M;
int bfs(int s, int t)
{
fill(parent, parent + N + 1, -1);
parent[s] = -2;
queue<pair<int, int>> q;
q.push({s, INF});
while (!q.empty())
{
int node = q.front().first;
int flow = q.front().second;
q.pop();
for (auto neigh : G[node])
{
if (capacity[node][neigh] > 0 && parent[neigh] == -1)
{
parent[neigh] = node;
int new_flow = min(flow, capacity[node][neigh]);
if (neigh == t)
{
return new_flow;
}
q.push({neigh, new_flow});
}
}
}
return 0;
}
int max_flow(int s, int t)
{
int max_flow = 0;
int path_flow;
while ((path_flow = bfs(s, t)))
{
max_flow += path_flow;
int curr = t;
while (curr != s)
{
int prev = parent[curr];
capacity[curr][prev] += path_flow;
capacity[prev][curr] -= path_flow;
curr = prev;
}
}
return max_flow;
}
int main()
{
fin >> N >> M;
for (int i = 0; i < M; i++)
{
int x, y, c;
fin >> x >> y >> c;
capacity[x][y] += c;
G[x].push_back(y);
}
fout << max_flow(1, N);
return 0;
}