Pagini recente » Cod sursa (job #3315109) | Cod sursa (job #3322041) | Cod sursa (job #3336691) | Cod sursa (job #3336535) | Cod sursa (job #3336994)
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
const int NMAX = 105;
const int INF = 1e9;
int capacity[NMAX][NMAX];
int parent[NMAX];
vector<int> G[NMAX];
int N, M;
int bfs(int s, int t)
{
fill(parent, parent + N + 1, -1);
parent[s] = 0;
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 (parent[neigh] == -1 && capacity[node][neigh] > 0)
{
int new_flow = min(flow, capacity[node][neigh]);
parent[neigh] = node;
if (neigh == t)
return new_flow;
q.push({neigh, new_flow});
}
}
}
return 0;
}
int edmonds_karp(int s, int t)
{
int max_flow = 0;
int current_flow;
while ((current_flow = bfs(s, t)))
{
max_flow += current_flow;
int curr = t;
while (curr != s)
{
int next = parent[curr];
capacity[next][curr] -= current_flow;
capacity[curr][next] += current_flow;
curr = next;
}
}
return max_flow;
}
int main()
{
fin >> N >> M;
for (int i = 0; i < M; i++)
{
int x, y, c;
fin >> x >> y >> c;
G[x].push_back(y);
G[y].push_back(x);
capacity[x][y] += c;
}
int max_flow = edmonds_karp(1, N);
fout << max_flow;
return 0;
}