Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <cstdio>
- #include <queue>
- #include <algorithm>
- using namespace std;
- typedef long long llint;
- const int MAXN = 5000;
- const int MAXM = 30000;
- const int MAXE = 2*MAXM;
- int n, m, e;
- int src, sink;
- int last[MAXN], dist[MAXN], curr[MAXN];
- int next[MAXE], cap[MAXE], adj[MAXE];
- void make_edge( int a, int b, int c ) {
- adj[e] = b;
- cap[e] = c;
- next[e] = last[a];
- last[a] = e++;
- }
- bool init_graph() {
- for( int i = 0; i < n; ++i ) {
- curr[i] = last[i];
- dist[i] = -1;
- }
- queue<int> Q;
- Q.push( src );
- dist[src] = 0;
- while( !Q.empty() ) {
- int x = Q.front(); Q.pop();
- for( int e = last[x]; e != -1; e = next[e] ) {
- if( cap[e] > 0 && dist[adj[e]] == -1 ) {
- Q.push( adj[e] );
- dist[adj[e]] = dist[x] + 1;
- }
- }
- }
- return dist[sink] != -1;
- }
- int push( int x, int flow ) {
- if( x == sink ) return flow;
- for( int &e = curr[x]; e != -1; e = next[e] ) {
- if( cap[e] == 0 || dist[x] + 1 != dist[adj[e]] ) continue;
- int f = push( adj[e], min( flow, cap[e] ) );
- if( f > 0 ) {
- cap[e] -= f;
- cap[e^1] += f;
- return f;
- }
- }
- return 0;
- }
- llint dinic() {
- llint ret = 0;
- while( init_graph() ) {
- for( ;; ) {
- int f = push( src, 1000000000 );
- if( f == 0 ) break;
- ret += f;
- }
- }
- return ret;
- }
- int main( void ) {
- scanf( "%d%d", &n, &m );
- for( int i = 0; i < n; ++i ) last[i] = -1;
- for( int i = 0; i < m; ++i ) {
- int a, b, c;
- scanf( "%d%d%d", &a, &b, &c ); --a, --b;
- make_edge( a, b, c );
- make_edge( b, a, c );
- }
- src = 0;
- sink = n-1;
- printf( "%lld\n", dinic() );
- return 0;
- }
Add Comment
Please, Sign In to add comment