Pagini recente » Cod sursa (job #3350404) | Cod sursa (job #1670183) | Cod sursa (job #738563) | Cod sursa (job #725959) | Cod sursa (job #3337207)
#include <iostream>
#include <vector>
#include <queue>
#include <climits>
#define pii pair<int, int>
using namespace std;
const int NMAX = 1005;
const char nl = '\n';
const int INF = LLONG_MAX;
vector<int> graph[NMAX];
vector<int> rev_graph[NMAX];
long long capacity[NMAX][NMAX];
long long flow[NMAX][NMAX];
int visited[NMAX];
int father[NMAX];
bool bfs(int source, int size) {
for(int i = 1; i <= size; ++i) {
father[i] = 0;
visited[i] = 0;
}
queue<int> q;
q.push(source);
while(!q.empty()) {
int node = q.front();
q.pop();
visited[node] = 1;
for(auto neigh: graph[node]) {
if(!visited[neigh] && capacity[node][neigh] - flow[node][neigh] > 0) {
father[neigh] = node;
visited[neigh] = 1;
q.push(neigh);
if(neigh == size) {
return true;
}
}
}
for(auto neigh: rev_graph[node]) {
if(!visited[neigh] && flow[node][neigh] > 0) {
father[neigh] = -node;
visited[neigh] = 1;
q.push(neigh);
if(neigh == size) {
return true;
}
}
}
}
return false;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
freopen("maxflow.in", "r", stdin);
freopen("maxflow.out", "w", stdout);
int n, m;
cin >> n >> m;
for(int i = 0; i < m; ++i) {
int u, v, w;
cin >> u >> v >> w;
graph[u].push_back(v);
rev_graph[v].push_back(u);
capacity[u][v] = w;
}
long long max_flow = 0;
while(bfs(1, n)) {
long long residual_capacity = INF;
int node = n;
while(node != 1) {
if(father[node] > 0) {
residual_capacity = min(residual_capacity, capacity[father[node]][node] - flow[father[node]][node]);
node = father[node];
} else {
residual_capacity = min(residual_capacity, flow[-father[node]][node]);
node = -father[node];
}
}
node = n;
while(node != 1) {
if(father[node] > 0) {
flow[father[node]][node] += residual_capacity;
node = father[node];
} else {
flow[-father[node]][node] -= residual_capacity;
node = -father[node];
}
}
max_flow += residual_capacity;
}
cout << max_flow << nl;
return 0;
}