Cod sursa(job #1309455)

Utilizator danalex97Dan H Alexandru danalex97 Data 5 ianuarie 2015 19:18:02
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.74 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <cstring>
#include <queue>
using namespace std;

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

const int N = 1010;
const int M = 5010;

int n,m,cap[N][N],dad[N],mark[N];
vector<int> v[N];

int send_flow(int src)
{
    dad[src] = -1;
    memset(mark,0,sizeof(mark));

    queue<int> q;
    q.push(src);
    mark[src] = 1;

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

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

    return mark[n];
}

int main()
{
    F>>n>>m;
    for (int i=1,x,y,c;i<=m;++i)
    {
        F>>x>>y>>c;
        cap[x][y] = c;
        v[x].push_back(y);
        v[y].push_back(x);
    }

    int flow = 0;
    while ( send_flow(1) )
        for (int i=0;i<int(v[n].size());++i)
        {
            int x = v[n][i];
            if ( !(mark[x] && cap[x][n] > 0) ) continue;

            int cp = cap[x][n];
            int wh = x;
            int y = x;
            x = dad[x];
            while ( x != -1 )
            {
                cp = min(cp,cap[x][y]);
                y = x;
                x = dad[x];
            }

            x = wh;
            y = x;
            x = dad[x];
            while ( x != -1 )
            {
                cap[x][y] -= cp;
                cap[y][x] += cp;
                y = x;
                x = dad[x];
            }
            cap[wh][n] -= cp;

            flow += cp;
        }
    G<<flow<<'\n';
}