Cod sursa(job #279920)

Utilizator marcelcodreaCodrea Marcel marcelcodrea Data 13 martie 2009 09:04:18
Problema Flux maxim de cost minim Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 2.1 kb
#include <stdio.h>   
#include <vector>   
  
using namespace std;   
  
#define maxn 510   
#define inf 2000000000   
#define ll long long   
  
int N, M, S, D;   
int Drum;   
vector <int> A[maxn];   
int G[maxn], Dist[maxn], From[maxn];   
int C[maxn][maxn], F[maxn][maxn], Cost[maxn][maxn];   
  
int BellmanFord()   
{   
    int i, j, stop = 0;   
  
    for (i = 1; i <= N; i++)   
    {   
           
        Dist[i] = inf;   
        From[i] = -1;   
    }   
  
    Dist[S] = 0;   
  
    while (!stop)   
    {   
        stop = 1;   
  
        for (i = 1; i <= N; i++)   
            for (j=0; j<G[i]; j++)   
                if (C[i][A[i][j]]-F[i][A[i][j]]>0 && Dist[i]+Cost[i][A[i][j]]<Dist[A[i][j]])   
                {   
                    Dist[A[i][j]] = Dist[i] + Cost[i][A[i][j]];   
                    From[A[i][j]] = i;   
                    stop = 0;   
                }   
    }   
  
    if (Dist[D] != inf)    
    {   
        int Vmin = inf;   
        Drum = 1;   
  
        for (i = D; i != S; i = From[i]) Vmin = min(Vmin, C[From[i]][i] - F[From[i]][i]);   
  
        for (i = D; i != S; i = From[i])    
        {   
            F[From[i]][i] += Vmin;   
            F[i][From[i]] -= Vmin;   
        }   
  
        return Vmin * Dist[D];   
    }   
  
    return 0;   
}   
  
ll Flux()   
{   
    ll Rez = 0;   
    Drum = 1;   
  
    while (Drum)   
    {   
        Drum = 0;   
        Rez += BellmanFord();   
    }   
  
    return Rez;   
}   
  
int main()   
{   
    freopen("fmcm.in", "r", stdin);   
    freopen("fmcm.out", "w", stdout);   
  
    int i, x, y, z, cap;   
  
    scanf("%d %d %d %d ", &N, &M, &S, &D);   
  
    for (i = 1; i <= M; i++)   
    {   
        scanf("%d %d %d %d ", &x, &y, &cap, &z);   
  
        A[x].push_back(y);   
        A[y].push_back(x);   
  
        C[x][y] = cap;   
        Cost[x][y] = z;   
        Cost[y][x] = -z;   
    }   
  
    for (i = 1; i <= N; i++) G[i] = A[i].size();   
  
    printf("%lld\n", Flux());   
  
    return 0;   
}