Pagini recente » Cod sursa (job #1441430) | Cod sursa (job #1741541) | Cod sursa (job #3263930) | Cod sursa (job #3258608) | Cod sursa (job #2709013)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
class MaxFlowSolver
{
int n, fmax;
std::vector<int> t;
std::vector<std::vector<int>> cap, flow, g;
std::vector<bool> vis;
void bfs(int startNode)
{
vis.assign(n + 1, false);
std::queue<int> q;
q.push(startNode);
vis[startNode] = true;
t[startNode] = 0;
while(!q.empty())
{
int node = q.front();
q.pop();
if(node == n)
continue;
for(int y : g[node])
if(cap[node][y] != flow[node][y])
{
if(!vis[y])
{
vis[y] = true;
t[y] = node;
q.push(y);
}
}
}
}
public:
MaxFlowSolver(int _n)
{
n = _n;
fmax = 0;
cap.resize(n + 1, std::vector<int>(n + 1));
flow.resize(n + 1, std::vector<int>(n + 1));
g.resize(n + 1);
t.resize(n + 1);
}
void addEdge(int x, int y, int c)
{
g[x].push_back(y);
g[y].push_back(x);
cap[x][y] = c;
}
int solve()
{
fmax = 0;
do
{
bfs(1);
if(vis[n] == false)
break;
for(int y : g[n])
{
if(vis[y] == false || cap[y][n] == flow[y][n])
continue;
t[n] = y;
int fmin = 1 << 30;
for(int node = n; node != 1; node = t[node])
fmin = std::min(fmin, cap[t[node]][node] - flow[t[node]][node]);
if(fmin == 0)
continue;
fmax += fmin;
for(int node = n; node != 1; node = t[node])
{
flow[t[node]][node] += fmin;
flow[node][t[node]] -= fmin;
}
}
} while(vis[n]);
return fmax;
}
};
using namespace std;
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
int n, m;
int main()
{
fin >> n >> m;
MaxFlowSolver maxFlowSolver(n);
for(int i = 0; i < m; i++)
{
int x, y, c;
fin >> x >> y >> c;
maxFlowSolver.addEdge(x, y, c);
}
fout << maxFlowSolver.solve() << '\n';
fin.close();
fout.close();
return 0;
}
/*
*/