Cod sursa(job #1239097)

Utilizator danalex97Dan H Alexandru danalex97 Data 8 octombrie 2014 10:52:50
Problema Flux maxim Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 1.57 kb
#include <fstream>
#include <iostream>
#include <vector>
#include <cstring>
#include <queue>
using namespace std;

ifstream F("maxflow.in");
ofstream G("maxflow.out");

const int N = 1010;

int n,m,ans,from[N],c[N][N];
vector<int> v[N];

bool find_paths()
{
    memset(from,0,sizeof(from));
    queue<int> q;
    from[1] = 1;
    q.push( 1 );

    while ( !q.empty() )
    {
        int x = q.front();
        q.pop();

        for (int i=0;i<int(v[x].size());++i)
        {
            int y = v[x][i];
            if ( c[x][y] > 0 && from[y] == 0 )
            {
                q.push(y);
                from[y] = x;
            }
        }
    }

    return from[n];
}

int main()
{
    F>>n>>m;
    for (int i=1,x,y,cc;i<=m;++i)
    {
        F>>x>>y>>cc;
        c[x][y] = cc;
        v[ x ].push_back( y );
        v[ y ].push_back( x );
    }
    while ( find_paths() )
        for (int i=0;i<int(v[n].size());++i)
        {
            int y = v[n][i];
            if ( c[y][n] != 0 && from[y] != 0 )
            {
                int x = y;
                int flow = 1<<30;
                while ( x != from[x] )
                {
                    flow = min(flow,c[from[x]][x]);
                    x = from[x];
                }
                ans += flow;
                x = y;
                while ( x != from[x] )
                {
                    c[from[x]][x] -= flow;
                    c[x][from[x]] += flow;
                    x = from[x];
                }
            }
        }
    G<<ans<<'\n';
}