Pagini recente » Cod sursa (job #3271564) | Cod sursa (job #881965) | Cod sursa (job #2651432) | Cod sursa (job #1576194) | Cod sursa (job #3271759)
#include<bits/stdc++.h>
using namespace std;
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
int n,m;
int capacitate[1005][1005], flux[1005][1005];
vector<vector<int>> adj(5005);
int bfs(int s, int t) {
vector<int> vis(5005,0);
vector<int> p(5005,-1);
queue<int> q;
q.push(s);
vis[s] = 1;
while (!q.empty()) {
int from = q.front();
q.pop();
for (auto to : adj[from]) {
if (!vis[to]) {
if ((capacitate[from][to] - flux[from][to]) > 0) {
q.push(to);
vis[to] = 1;
p[to] = from;
}
}
}
}
if (vis[t] == 0) {
return 0;
}
int x = t;
vector<int> path;
while (x!= -1) {
path.push_back(x);
x = p[x];
}
reverse(path.begin(),path.end());
int flow = INT_MAX;
for (int i = 0 ; i < path.size() - 1 ; i ++) {
int from = path[i];
int to = path[i+1];
flow = min(flow, capacitate[from][to] - flux[from][to]);
}
for (int i = 0 ; i < path.size() - 1; i ++) {
int from = path[i];
int to = path[i + 1];
flux[from][to] += flow;
flux[to][from] += flow;
}
return flow;
}
int main() {
fin >> n >> m;
for (int i = 1 ; i <= m ; i++) {
int x, y, c;
fin >> x >> y >> c;
capacitate[x][y] = c;
adj[x].push_back(y);
adj[y].push_back(x);
}
int max_flow = 0;
while (1) {
int flow = bfs(1,n);
if (flow == 0) {
break;
}
max_flow += flow;
}
fout << max_flow;
}