Pagini recente » Cod sursa (job #353300) | Cod sursa (job #1378429) | Cod sursa (job #1182584) | Cod sursa (job #2572472) | Cod sursa (job #3036580)
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream cin("maxflow.in");
ofstream cout("maxflow.out");
const int MAX = 1e3 + 1;
int flow[MAX][MAX] , cap[MAX][MAX] , sink , n , m , f , x , y;
vector <int> g[MAX];
struct Dinic{
int level[MAX] , ef[MAX];
bool bfs( int source = 1){
queue <int> q;
q.push(source);
for(int i = 1 ; i <= n ; i++){
level[i] = ef[i] = 0;
}
level[source] = 1;
while(!q.empty()){
x = q.front();
q.pop();
for(auto it : g[x]){
if(!level[it] && (cap[x][it] - flow[x][it] > 0 )){
level[it] = level[x] + 1;
q.push(it);
}
}
}
return (level[sink] != 0);
}
int dfs( int x , int fl){
if(x == sink){
return fl;
}
int sz = g[x].size();
for(int &h = ef[x] ; h < sz ; h++){
int it = g[x][h];
if((level[it] == level[x] + 1) && (cap[x][it] - flow[x][it] > 0)){
int new_flow = dfs(it,min(fl,cap[x][it]-flow[x][it]));
if(new_flow){
flow[x][it] += new_flow;
flow[it][x] -= new_flow;
return new_flow;
}
}
}
return 0;
}
int solve(){
int total_flow = 0;
while(bfs()){
int new_flow = dfs(1,1e9);
while(new_flow){
total_flow += new_flow;
new_flow = dfs(1,1e9);
}
}
return total_flow;
}
}d;
int main(){
cin >> n >> m;
while(m--){
cin >> x >> y >> f;
cap[x][y] = f;
g[x].push_back(y);
g[y].push_back(x);
}
sink = n;
cout << d.solve();
return 0;
}