Pagini recente » Cod sursa (job #1766743) | Cod sursa (job #1749651) | Cod sursa (job #1033091) | Cod sursa (job #564518) | Cod sursa (job #2416940)
#include <queue>
#include <vector>
#include <climits>
#include <fstream>
#include <algorithm>
using std::fill;
using std::queue;
using std::vector;
std::ifstream fin("maxflow.in");
std::ofstream fout("maxflow.out");
inline int min(int x, int y) {
return x < y ? x : y;
}
class FlowNetwork {
private:
int n;
vector<vector<int>> ad;
vector<vector<int>> cap;
bool bfs(vector<bool>& vis, vector<int>& father) {
fill(vis.begin(), vis.end(), false);
vis[1] = true;
queue<int> q;
q.push(1);
while (!q.empty()) {
int node = q.front(); q.pop();
for (int nghb : ad[node])
if (!vis[nghb] && cap[node][nghb]) {
vis[nghb] = true;
father[nghb] = node;
if (nghb != n)
q.push(nghb);
}
}
return vis[n];
}
public:
FlowNetwork(int n) {
this->n = n;
ad.resize(n + 1);
cap.resize(n + 1, vector<int>(n + 1));
}
void addEdge(int x, int y, int z) {
ad[x].push_back(y);
ad[y].push_back(x);
cap[x][y] = z;
}
int getMaxFlow() {
int maxFlow = 0;
vector<bool> vis(n + 1);
vector<int> father(n + 1);
while (bfs(vis, father))
for (int nghb : ad[n])
if (vis[nghb] && cap[nghb][n]) {
int flow = INT_MAX;
father[n] = nghb;
for (int i = n; i != 1; i = father[i])
flow = min(flow, cap[father[i]][i]);
for (int i = n; i != 1; i = father[i]) {
cap[father[i]][i] -= flow;
cap[i][father[i]] += flow;
}
maxFlow += flow;
}
return maxFlow;
}
};
int main() {
int n, m;
fin >> n >> m;
FlowNetwork network(n);
for (int i = 0; i < m; i++) {
int x, y, z; fin >> x >> y >> z;
network.addEdge(x, y, z);
}
fout << network.getMaxFlow() << '\n';
fout.close();
return 0;
}