Cod sursa(job #988804)

Utilizator danalex97Dan H Alexandru danalex97 Data 23 august 2013 21:29:03
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.19 kb
#include <fstream>
#include <queue>
#include <cstring>
#include <vector>
using namespace std;

const int Nmax = 1010;
const int Mmax = 5010;

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

#define IT(type) vector<type>::iterator

int N,M,total_flow;
vector<int> V[Nmax];
vector<int> neighbours;

int capacity[Nmax][Nmax];
int last[Nmax],Cmin[Nmax];

int find_paths(int source,int target)
{
    queue<int> Q;
    memset(last,0,sizeof(last));

    last[source] = -1;
    Q.push( source );

    while ( Q.size() )
    {
        int node = Q.front();
        Q.pop();

        for (IT(int) where=V[node].begin();where!=V[node].end();++where)
            if ( capacity[node][*where] > 0 && last[*where] == 0 )
            {
                last[*where] = node;
                Q.push( *where );
            }
    }

    neighbours.clear();

    for (IT(int) node=V[target].begin();node!=V[target].end();++node)
        if ( last[ *node ] != 0 && capacity[*node][target] > 0 )
            neighbours.push_back( *node );

    if ( last[target] == 0 )
        return 0;
    return 1;
}

int main()
{
    F>>N>>M;
    for (int i=1,x,y,c;i<=M;++i)
    {
        F>>x>>y>>c;
        if ( capacity[x][y] == 0 && capacity[y][x] == 0 )
        {
            V[ x ].push_back( y );
            V[ y ].push_back( x );
        }
        capacity[x][y] += c;
    }

    int source = 1;
    int target = N;

    while ( find_paths(source,target) != 0 )
    {
        int debug = 1;
        for (IT(int) neighbour=neighbours.begin();neighbour!=neighbours.end();++neighbour)
        {
            Cmin[*neighbour] = capacity[*neighbour][target];
            for (int now=*neighbour;now!=source;now=last[now])
                Cmin[*neighbour] = min( Cmin[*neighbour] , capacity[last[now]][now] );
            total_flow += Cmin[*neighbour];

            for (int now=*neighbour;now!=source;now=last[now])
            {
                capacity[last[now]][now] -= Cmin[*neighbour];
                capacity[now][last[now]] += Cmin[*neighbour];
            }
            capacity[*neighbour][target] -= Cmin[*neighbour];
        }
    }

    G<<total_flow<<'\n';
}