Cod sursa(job #1611231)

Utilizator CiurezAndreiCiurez Marius-Andrei CiurezAndrei Data 23 februarie 2016 23:32:50
Problema Flux maxim de cost minim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.84 kb
#include<fstream>
#include<vector>
#include<queue>
#include<bitset>
#include<algorithm>
using namespace std;

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

#define INFINITY (1<<30)

int N, M,S,D;
vector<int> L[360];
queue<int> Q;
bitset<360> viz;
int DIST[360];
int C[360][360],F[360][360],COST[360][360],T[360],sol;
bool BellmanFord()
{
    for (int i = 1;i <= N;++i)
        DIST[i] = INFINITY;
    viz.reset();

    Q.push(S);
    DIST[S] = 0;

    while (!Q.empty())
    {
        int node = Q.front();
        Q.pop();
        viz[node] = 0;
        for (int i = 0;i < L[node].size();++i)
        {
            if ((DIST[node] + COST[node][L[node][i]] < DIST[ L[node][i] ]) && (F[node][L[node][i]] < C[node][L[node][i]]))
            {
                DIST[L[node][i]] = DIST[node] + COST[node][L[node][i]];
                T[L[node][i]] = node;
                if (viz[L[node][i]] == 0)
                {
                    viz[L[node][i]] = 1;
                    Q.push(L[node][i]);
                }
            }
        }
    }

    if (DIST[D] != INFINITY)
        return true;
    return false;

}

int main()
{
    in >> N >> M>>S>>D;


    for (int i = 1;i <= M;++i)
    {
        int x, y, c, z;
        in >> x >> y >> c >> z;
        C[x][y] = c;
        COST[x][y] = z;
        COST[y][x] = -z;
        L[x].push_back(y);
        L[y].push_back(x);
    }

    while (BellmanFord())
    {
        int MIN = INFINITY;
        int x = D;
        while (x!=S)
        {
            MIN = min(MIN, C[T[x]][x]-F[T[x]][x]);
            x = T[x];
        }
        x = D;
        while (x!=S)
        {
            sol += MIN*COST[T[x]][x];
            F[T[x]][x] += MIN;
            F[x][T[x]] -= MIN;
            x = T[x];
        }

    }

    out << sol;

    return 0;
}