Pagini recente » Cod sursa (job #2941626) | Cod sursa (job #36799) | Cod sursa (job #37666) | Cod sursa (job #3252777) | Cod sursa (job #3234589)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
const int kN = 1e3;
const int kInf = 1e9;
int n, m;
vector<int> adj[kN + 1];
int parent[kN + 1];
int cap[kN + 1][kN + 1], flow[kN + 1][kN + 1];
void minSelf(int &x, int y) {
if(y < x) {
x = y;
}
}
void addEdge(int u, int v, int c) {
cap[u][v] = c;
flow[u][v] = 0;
adj[u].emplace_back(v);
adj[v].emplace_back(u);
}
bool bfs(int s, int d) {
for(int i = 1; i <= n; i++) {
parent[i] = 0; // parent este in acelasi timp un vector de vizitati
}
queue<int> q;
q.push(s);
parent[s] = s;
while(!q.empty()) {
int node = q.front();
q.pop();
for(const auto &it: adj[node]) {
if(parent[it] || flow[node][it] == cap[node][it]) {
continue;
}
q.push(it);
parent[it] = node;
}
}
return parent[d];
}
int bottleneck(int s, int d) {
int res = kInf;
for(int p = d; p != s; p = parent[p]) {
minSelf(res, cap[parent[p]][p] - flow[parent[p]][p]);
}
return res;
}
void pushFlow(int s, int d, int f) {
for(int p = d; p != s; p = parent[p]) {
flow[p][parent[p]] -= f;
flow[parent[p]][p] += f;
}
}
int main() {
fin >> n >> m;
for(int i = 1; i <= m; i++) {
int u, v, c;
fin >> u >> v >> c;
addEdge(u, v, c);
}
int f = 0;
while(bfs(1, n)) {
for(const auto &it: adj[n]) {
parent[n] = it;
if(flow[it][n] == cap[it][n] || !parent[it]) {
continue;
}
int maxFlow = bottleneck(1, n);
if(maxFlow == 0) {
continue;
}
pushFlow(1, n, maxFlow);
f += maxFlow;
}
}
fout << f << '\n';
return 0;
}