Pagini recente » Cod sursa (job #2571454) | Cod sursa (job #3138631) | Cod sursa (job #2026686) | Cod sursa (job #1248928) | Cod sursa (job #2694468)
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>
using namespace std;
constexpr auto max_n = 1024;
constexpr auto inf = 0x3f3f3f3f;
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
int n, m;
vector<int> graph[max_n];
bool visited[max_n];
int costs[max_n][max_n];
int flows[max_n][max_n];
int parents[max_n];
bool bfs()
{
queue<int> nodes_queue;
nodes_queue.push(1);
memset(visited, false, sizeof visited);
visited[1] = true;
while (!nodes_queue.empty())
{
const auto crt_node = nodes_queue.front();
nodes_queue.pop();
for (auto neigh : graph[crt_node])
{
if (costs[crt_node][neigh] == flows[crt_node][neigh] || visited[neigh])
continue;
visited[neigh] = true;
nodes_queue.push(neigh);
parents[neigh] = crt_node;
}
}
return visited[n];
}
int main()
{
fin >> n >> m;
for (auto i = 0; i < m; i++)
{
int x, y, z;
fin >> x >> y >> z;
graph[x].push_back(y);
graph[y].push_back(x);
costs[x][y] += z;
}
auto flow = 0;
auto crt_flow = 0;
while (bfs())
{
for (auto& node : graph[n])
{
if (flows[node][n] == costs[node][n] || !visited[node])
continue;
parents[n] = node;
crt_flow = inf;
for (auto prev_node = n; prev_node != 1; prev_node = parents[prev_node])
crt_flow = min(crt_flow, costs[parents[prev_node]][prev_node] - flows[parents[prev_node]][prev_node]);
if (crt_flow == 0)
continue;
for (auto prev_node = n; prev_node != 1; prev_node = parents[prev_node])
{
flows[parents[prev_node]][prev_node] += crt_flow;
flows[prev_node][parents[prev_node]] -= crt_flow;
}
flow += crt_flow;
}
}
fout << flow;
return 0;
}