Pagini recente » Cod sursa (job #1962621) | Cod sursa (job #2659712) | Cod sursa (job #804394) | Cod sursa (job #1636957) | Cod sursa (job #3041996)
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
const int nmax = 1e3;
struct graph {
int n;
void init ( int _n ) {
n = _n;
}
struct edge {
int from;
int to;
int cap;
};
vector < edge > e;
vector < int > g[nmax];
int dist[nmax];
int rem[nmax];
void add_edges ( int from, int to, int cap ) {
g[from].push_back ( e.size () );
e.push_back ( { from, to, cap } );
g[to].push_back ( e.size () );
e.push_back ( { to, from, 0 } );
}
int bfs ( int start, int dest ) {
for ( int i = 0; i < n; i++ )
dist[i] = 0;
queue < int > q;
dist[start] = 1;
q.push ( start );
while ( ! q.empty () ) {
int node = q.front ();
q.pop ();
for ( int &x: g[node] )
if ( dist[e[x].to] == 0 && e[x].cap > 0 ) {
dist[e[x].to] = dist[node] + 1;
q.push ( e[x].to );
}
}
return dist[dest];
}
int dfs ( int node, int sink, int flow ) {
if ( node == sink || flow == 0 ) return flow;
for ( int &ind = rem[node]; ind < g[node].size (); ind++ ) {
int e_id = g[node][ind];
int vec = e[e_id].to;
int cap = e[e_id].cap;
if ( dist[vec] == dist[node] + 1 && cap > 0 ) {
int fl = dfs ( vec, sink, min ( flow, cap ) );
if ( fl > 0 ) {
e[e_id].cap -= fl;
e[e_id ^ 1].cap += fl;
return fl;
}
}
}
return 0;
}
int max_flow ( int source, int sink ) {
int flow = 0;
while ( bfs ( source, sink ) ) {
for ( int i = 0; i < n; i++ )
rem[i] = 0;
int f;
while ( f = dfs ( source, sink, 1e9 ) )
flow += f;
}
return flow;
}
} graph;
ifstream fin ( "maxflow.in" );
ofstream fout ( "maxflow.out" );
int main() {
int n, m, a, b, c;
fin >> n >> m;
graph.init ( n );
for ( int i = 0; i < m; i++ ) {
fin >> a >> b >> c;
a--, b--;
graph.add_edges ( a, b, c );
}
fout << graph.max_flow ( 0, n - 1 );
return 0;
}