Pagini recente » Cod sursa (job #1879319) | Cod sursa (job #294061) | Cod sursa (job #2391252) | Cod sursa (job #301716) | Cod sursa (job #2961014)
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
using namespace std;
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
int N, M;
vector <int> capacity[1005], adj[1005];
int BFS(int start, int end, vector<int>& parent)
{
parent.resize(N + 1);
fill(parent.begin(), parent.end(), -1);
parent[start] = -2;
queue <pair <int, int>> q;
q.push({ start, INT_MAX });
while (!q.empty())
{
int current = q.front().first;
int flow = q.front().second;
q.pop();
for (int next : adj[current])
{
if (parent[next] == -1 && capacity[current][next])
{
parent[next] = current;
int new_flow = min(flow, capacity[current][next]);
if (next == end)
return new_flow;
q.push({ next, new_flow });
}
}
}
return 0;
}
int MaxFlow(int start, int end)
{
int flow = 0;
vector<int> parent(N);
int new_flow;
while (new_flow = BFS(start, end, parent))
{
flow += new_flow;
int current = end;
while (current != start)
{
int prev = parent[current];
capacity[prev][current] -= new_flow;
capacity[current][prev] += new_flow;
current = prev;
}
}
return flow;
}
int main()
{
fin >> N >> M;
int source = 1, dest = N;
for (int i = 0; i <= N; i++)
{
adj[i].resize(N + 1);
capacity[i].resize(N + 1);
}
for (int edge = 0; edge < M; edge++)
{
int x, y, cap;
fin >> x >> y >> cap;
capacity[x][y] = cap;
adj[x].push_back(y);
adj[y].push_back(x);
}
int maxFlow = MaxFlow(source, dest);
fout << maxFlow << endl;
}