Pagini recente » Cod sursa (job #2528400) | Cod sursa (job #1150226) | Cod sursa (job #1580905) | Cod sursa (job #1396011) | Cod sursa (job #2408286)
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <queue>
#include <limits>
using namespace std;
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
int const inf = numeric_limits<int>::max();
int n, m;
int bfs(vector<vector<int>> const &adjList, vector<vector<int>> &capacity, vector<int> &parent)
{
fill(parent.begin(), parent.end(), -1);
parent[1] = -2;
queue<pair<int, int>> Q;
Q.push(make_pair(1, inf));
while (Q.empty() == false)
{
int current = Q.front().first;
int flow = Q.front().second;
Q.pop();
for (auto next : adjList[current])
{
if (parent[next] == -1 && capacity[current][next])
{
parent[next] = current;
int new_flow = min(flow, capacity[current][next]);
if (next == n)
return new_flow;
Q.push(make_pair(next, new_flow));
}
}
}
return 0;
}
void maxflow(vector<vector<int>> const &adjList, vector<vector<int>> &capacity)
{
int flow = 0;
vector<int> parent(n + 1);
int new_flow;
while (new_flow = bfs(adjList, capacity, parent))
{
flow += new_flow;
int current = n;
while (current != 1)
{
int prev = parent[current];
capacity[prev][current] -= new_flow;
capacity[current][prev] += new_flow;
current = prev;
}
}
fout << flow;
}
int main()
{
fin >> n >> m;
vector<vector<int>> capacity(n + 1, vector<int>(n + 1, 0)), adjList(n + 1);
for (int i = 0; i < m; i++)
{
int x, y, z;
fin >> x >> y >> z;
adjList[x].push_back(y);
adjList[y].push_back(x);
capacity[x][y] = z;
}
maxflow(adjList, capacity);
return 0;
}