Pagini recente » Cod sursa (job #1661465) | Cod sursa (job #472017) | Cod sursa (job #2824140) | Cod sursa (job #666880) | Cod sursa (job #1437288)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <limits>
#include <algorithm>
using FlowGraph = std::vector<std::vector<int>>;
const int NONE = -1;
std::vector<int>
augmentingPath(
const FlowGraph &graph,
int source,
int sink
)
{
std::vector<int> parent(graph.size(), NONE);
std::queue<int> bfsQueue;
bfsQueue.emplace(source);
while (parent[sink] == NONE && bfsQueue.size() > 0) {
auto u = bfsQueue.front();
bfsQueue.pop();
for (auto v = 0u; v < graph.size(); ++v)
if (graph[u][v] > 0 && parent[v] == NONE) {
parent[v] = u;
bfsQueue.emplace(v);
}
}
if (parent[sink] == NONE)
return std::vector<int>{};
auto node = sink;
std::vector<int> path{sink};
do {
node = parent[node];
path.emplace_back(node);
} while (node != source);
std::reverse(path.begin(), path.end());
return path;
}
int maxFlow(FlowGraph &graph, int source, int sink)
{
auto maxFlow = 0;
while (true) {
auto augPath = augmentingPath(graph, source, sink);
if (!augPath.size())
break;
auto min = std::numeric_limits<int>::max();
for (auto i = 0u; i < augPath.size() - 1; ++i)
min = std::min(min, graph[augPath[i]][augPath[i + 1]]);
maxFlow += min;
for (auto i = 0u; i < augPath.size() - 1; ++i) {
auto fst = augPath[i];
auto snd = augPath[i + 1];
graph[fst][snd] -= min;
graph[snd][fst] += min;
}
}
return maxFlow;
}
int main()
{
std::ifstream fin{"maxflow.in"};
std::ofstream fout{"maxflow.out"};
int N, M;
fin >> N >> M;
FlowGraph graph(N, std::vector<int>(N, 0));
for (auto i = 0; i < M; ++i) {
int x, y, c;
fin >> x >> y >> c;
graph[x - 1][y - 1] = c;
}
fout << maxFlow(graph, 0, N - 1) << std::endl;
return 0;
}