Cod sursa(job #975837)

Utilizator crisbodnarCristian Bodnar crisbodnar Data 21 iulie 2013 19:21:39
Problema Flux maxim de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.2 kb
#include <iostream>
#include <fstream>
#include <algorithm>
#include <queue>
#include <cstring>
#include <vector>

using namespace std;

#define uns unsigned
#define newn a[x][i]
#define f first
#define s second

ifstream fin("fmcm.in");
ofstream fout("fmcm.out");

const int N = 355;
const int oo = 0x3f3f3f3f;

int n, m, s, d, sol, c[N][N], cst[N][N], ds[N], cr[N], ci[N], t[N];
typedef pair <int, int> nod;
priority_queue <nod, vector<nod>, greater<nod> > h;
vector <bool> qu(N);
vector <int> a[N];
queue <int> q;

void Bellman_Ford()
{
    for(q.push(s), ds[s] = 0, qu[s] = 1; !q.empty(); q.pop())
    {
        int x = q.front();
        for(uns i=0; i<a[x].size(); i++)
            if(c[x][newn] && ds[x] + cst[x][newn] < ds[newn])
            {
                ds[newn] = ds[x] + cst[x][newn];
                if(!qu[newn]) qu[newn] = 1, q.push(newn);
            }
    }
}

inline bool Dijkstra()
{
    memset(ci, oo, sizeof(ci));
    for(cr[s] = ci[s] = 0, h.push(nod(0, s)); !h.empty();)
    {
        int x = h.top().s, val = h.top().f; h.pop();
        if (val != ci[x]) continue;
        for(uns i=0; i<a[x].size(); i++)
            if(c[x][newn])
            {
                int newc = ci[x] + cst[x][newn] + ds[x] - ds[newn];
                if(newc < ci[newn])
                {
                    ci[newn] = newc;
                    cr[newn] = cr[x] + cst[x][newn];
                    h.push(nod(ci[newn], newn));
                    t[newn] = x;
                }
            }
    }
    return (ci[d] < oo);
}

int main()
{
    fin>>n>>m>>s>>d;
    memset(ds, oo, sizeof(ds));
    while(m--)
    {
        int x, y;
        fin>>x>>y;
        a[x].push_back(y);
        a[y].push_back(x);
        fin>>c[x][y]>>cst[x][y];
        cst[y][x] = -cst[x][y];
    }
    Bellman_Ford();
    while(Dijkstra())
    {
        memcpy(ds, cr, sizeof(ds));
        int fmin = oo;
        for(int j=d; j!=s; j=t[j])
            fmin = min(fmin, c[t[j]][j]);
        sol += fmin * cr[d];
        for(int j=d; j!=s; j=t[j])
        {
            c[t[j]][j] -= fmin;
            c[j][t[j]] += fmin;
        }
    }
    fout<<sol<<'\n';
    return 0;
}