Cod sursa(job #800892)

Utilizator danalex97Dan H Alexandru danalex97 Data 22 octombrie 2012 21:07:17
Problema Flux maxim de cost minim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.7 kb
#include <fstream>
#include <cstring>
#include <vector>
#include <queue>
using namespace std;

const int Nmax = 360;
const int oo = 0x3f3f3f3f;

vector<int> A[Nmax];
int C[Nmax][Nmax], D[Nmax][Nmax];

int N,M,Dad[Nmax],Flux,Start,Stop;
int Dist[Nmax],Marked[Nmax];

queue<int> Q;

typedef vector<int>::iterator IT;

bool Path()
{
    memset(Marked,0,sizeof(Marked));
    for (int i=1;i<=N;++i) Dist[i]=oo, Dad[i]=-1;
    Dist[Start]=0;

    for ( Marked[Start] = 1, Q.push(Start) ; Q.size() ; Marked[Q.front()] = 0 , Q.pop() )
        for ( IT it = A[Q.front()].begin() ; it!= A[Q.front()].end() ; ++it )
            if ( C[Q.front()][ *it ] > 0 && Dist[Q.front()] + D[Q.front()][*it] < Dist[*it] )
            {
                Dist[*it]=Dist[Q.front()]+D[Q.front()][*it];
                Dad[*it]=Q.front();
                if ( !Marked[*it] )
                {
                    Q.push( *it );
                    Marked[ *it ]=1;
                }
            }

    return Dist[Stop] != oo;
}

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

int main()
{
    F>>N>>M>>Start>>Stop;
    for (int i=1,x,y,c,d;i<=M;++i)
    {
        F>>x>>y>>c>>d;
        A[ x ].push_back( y );
        A[ y ].push_back( x );
        C[x][y]=c;
        D[x][y]=d;
        D[y][x]=-d;
    }

    for ( int Flow = oo; Path() ; Flux += Dist[Stop] * Flow )
    {
        Flow = oo;
        for ( int Nod = Stop ; Nod != Start ; Nod = Dad[Nod] )
            Flow = min ( Flow , C[ Dad[Nod] ][ Nod ] );
        for ( int Nod = Stop ; Nod != Start ; Nod = Dad[Nod] )
        {
            C[Dad[Nod]][Nod] -= Flow;
            C[Nod][Dad[Nod]] += Flow;
        }
    }
    G<<Flux<<'\n';
}