Pagini recente » Cod sursa (job #1831258) | Cod sursa (job #3323168) | Borderou de evaluare (job #1828961) | Cod sursa (job #1374677) | Cod sursa (job #3328579)
#include <bits/stdc++.h>
using namespace std;
const int NMAX = 1e3;
int capacitate[NMAX + 1][NMAX + 1];
int flux[NMAX + 1][NMAX + 1];
int vis[NMAX + 1], p[NMAX + 1];
vector<int> G[NMAX + 1];
int n, m;
int bfs(int s, int d) {
for(int i = 1; i <= n; i ++) {
vis[i] = 0;
}
queue <int> q;
q.push(s);
vis[s] = 1;
while(!q.empty()) {
int nod = q.front();
q.pop();
for(auto& v : G[nod]) {
if(!vis[v] && capacitate[nod][v] - flux[nod][v] > 0) {
vis[v] = 1;
p[v] = nod;
q.push(v);
}
}
}
if(!vis[d]) {
return 0;
}
vector<int> path;
int x = d;
while(x != 0) {
path.push_back(x);
x = p[x];
}
reverse(path.begin(), path.end());
int flow = 1e9;
for(int i = 0; i < path.size() - 1; i ++) {
int a = path[i];
int b = path[i + 1];
flow = min(flow, capacitate[a][b] - flux[a][b]);
}
for(int i = 0; i < path.size() - 1; i ++) {
int a = path[i];
int b = path[i + 1];
flux[a][b] += flow;
flux[b][a] -= flow;
}
return flow;
}
int main() {
ifstream cin("maxflow.in");
ofstream cout("maxflow.out");
cin >> n >> m;
for(int i = 1; i <= m; i ++) {
int x, y, cap;
cin >> x >> y >> cap;
G[x].push_back(y);
G[y].push_back(x);
capacitate[x][y] = cap;
}
int flux_maxim = 0;
int s = 1;
int d = n;
int flow;
while((flow = bfs(s, d)) > 0) {
flux_maxim += flow;
}
cout << flux_maxim << "\n";
return 0;
}