Cod sursa(job #769961)

Utilizator test_666013Testez test_666013 Data 21 iulie 2012 14:50:41
Problema Flux maxim de cost minim Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.6 kb
#include <cstdio>
#include <vector>
#include <set>
#include <algorithm>
using namespace std;
#define MAX 355
#define INF 0xfffffff

vector<int>g[MAX];
set<int>s1,s2;

int n,m,s,d,c[MAX][MAX],p[MAX][MAX],f[MAX][MAX],dist[MAX],tt[MAX];

bool drum(){
    int x,y;
    for(int i=1;i<=n;i++) dist[i] = INF;
    dist[s] = 0;
    s1.insert(s);
    for(int k=1;k<=n;k++)
    {
        while( s1.size()>0 )
        {
            x = *s1.begin(); s1.erase(s1.begin());
            for(int i=0;i<g[x].size();i++)
            {
                y = g[x][i];
                if( dist[y] > dist[x] + p[x][y] && c[x][y] > f[x][y] )
                {
                    dist[y] = dist[x] + p[x][y];
                    tt[y] = x;
                    s2.insert(y);
                }
            }
        }
        swap(s1,s2);
    }
    if( dist[d] < INF/2 )return 1; else return 0;
}

void rezolva(){
    int flux, cost = 0;
    while( drum() )
    {
        flux = INF;
        for(int x = d;x != s;x = tt[x]) flux = min(flux, c[tt[x]][x] - f[tt[x]][x]);
        for(int x = d;x != s;x = tt[x])
        {
            f[tt[x]][x] += flux;
            f[x][tt[x]] -= flux;
            cost += flux * p[tt[x]][x];
        }
    }
    printf("%d\n",cost);
}

int main(){
    int x,y,z,w;
    freopen("fmcm.in","r",stdin);
    freopen("fmcm.out","w",stdout);
        scanf("%d %d %d %d",&n,&m,&s,&d);
        while(m--)
        {
            scanf("%d %d %d %d",&x,&y,&z,&w);
            g[x].push_back(y);
            g[y].push_back(x);
            c[x][y] = z;
            p[x][y] = w;
            p[y][x] = -w;
        }
    rezolva();
    return 0;
}