Cod sursa(job #1411971)

Utilizator Al3ks1002Alex Cociorva Al3ks1002 Data 1 aprilie 2015 01:36:29
Problema Flux maxim de cost minim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 2.2 kb
#include<cstdio>
#include<fstream>
#include<iostream>
#include<iomanip>
#include<algorithm>
#include<vector>
#include<bitset>
#include<deque>
#include<queue>
#include<set>
#include<map>
#include<cmath>
#include<cstring>
#include<ctime>
#include<cstdlib>
#include<unordered_map>

#define ll long long
#define pb push_back
#define mp make_pair
#define pii pair<int,int>
#define pll pair<ll,ll>
#define all(x) (x).begin(), (x).end()
#define fi first
#define se second

using namespace std;

const int nmax = 355;
const int inf = (1LL << 31) - 1;

int i, n, m, source, sink, x, y, c, z, sol, add;
int flow[nmax][nmax], cap[nmax][nmax], cost[nmax][nmax];
int dist[nmax], f[nmax];
int mlc;

vector<int> v[nmax];
deque<int> q;
bitset<nmax> inq;

bool bf()
{
    for(i = 1; i <= n; i++)
    {
        dist[i] = inf;
        f[i] = 0;
    }

    dist[source] = 0;
    f[source] = source;
    inq[source] = 1;
    q.pb(source);

    while(!q.empty())
    {
        x = q.front();
        q.pop_front();
        inq[x] = 0;

        if(x == sink)
            continue;

        for(auto it : v[x])
            if(dist[x] + cost[x][it] < dist[it] && flow[x][it] < cap[x][it])
            {
                dist[it] = dist[x] + cost[x][it];
                f[it] = x;
                if(!inq[it])
                {
                    inq[it] = 1;
                    q.pb(it);
                }
            }
    }

    return dist[sink] != inf;
}

int main()
{
    freopen("fmcm.in", "r", stdin);
    freopen("fmcm.out", "w", stdout);

    scanf("%d%d%d%d", &n, &m, &source, &sink);

    for(; m; m--)
    {
        scanf("%d%d%d%d", &x, &y, &c, &z);

        v[x].pb(y);
        v[y].pb(x);

        cap[x][y] = c;
        cost[x][y] = z;
        cost[y][x] = -z;
    }

    while(bf())
    {
        mlc++;

        add = inf;

        for(x = sink; x != f[x]; x = f[x])
            add = min(add, cap[f[x]][x] - flow[f[x]][x]);

        for(x = sink; x != f[x]; x = f[x])
        {
            flow[f[x]][x] += add;
            flow[x][f[x]] -= add;
        }

        sol += dist[sink] * add;
    }

    printf("%d\n", sol);

    return 0;
}