Pagini recente » Cod sursa (job #2687077) | Cod sursa (job #3196727) | Cod sursa (job #2184993) | Cod sursa (job #1938342) | Cod sursa (job #2955080)
#include <bits/stdc++.h>
using namespace std;
ifstream f("maxflow.in");
ofstream g("maxflow.out");
const int NMAX = 1002;
int n, m, RG[NMAX][NMAX];
vector<pair<int, int>> G[NMAX];
void read(){
f >> n >> m;
for(int i = 1; i <= m; ++i){
int x, y, z;
f >> x >> y >> z;
G[x].push_back({y, z});
G[y].push_back({x, z});
RG[x][y] = z;
}
}
bool BFS(int s, int t, vector<int>& parent){
fill(parent.begin(), parent.end(), -1);
queue<int> Q;
Q.push(s);
parent[s] = -2;
while(!Q.empty()){
int node = Q.front();
Q.pop();
for(auto i : G[node]){
if(parent[i.first] == -1 && RG[node][i.first] > 0){
parent[i.first] = node;
if(i.first == t)
return true;
Q.push(i.first);
}
}
}
return false;
}
void solve(){
int max_flow = 0, s = 1, t = n;
vector<int> parent(NMAX, -1);
while(BFS(s, t, parent)){
for(auto i : G[n]){
if(parent[i.first] == -1 || RG[i.first][n] == 0) continue;
parent[n] = i.first;
int path_flow = INT_MAX;
// find the max flow through the path
for(int node = t; node != s; node = parent[node]){
int aux = parent[node];
path_flow = min(path_flow, RG[aux][node]);
}
if(path_flow == 0) continue;
// update
for(int node = t; node != s; node = parent[node]){
int aux = parent[node];
RG[aux][node] -= path_flow;
RG[node][aux] += path_flow;
}
max_flow += path_flow;
}
}
g << max_flow << '\n';
}
int main(){
read();
solve();
return 0;
}