Cod sursa(job #1517998)

Utilizator StarGold2Emanuel Nrx StarGold2 Data 5 noiembrie 2015 10:08:09
Problema Flux maxim de cost minim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 2.74 kb
#include <cstdio>
#include <queue>
#include <vector>
#include <algorithm>
#include <bitset>

#define DIM 512
#define INF 1000000000
using namespace std;

int startNode, finishNode;
int capacity, cost, node2;
int nrNodes, nrEdges, node1;

int Distance[DIM], Capacity[DIM][DIM];
int Cost[DIM][DIM], MaxFlow[DIM][DIM];
bitset <DIM> Marked; queue <int> Queue;
vector <int> Edges[DIM]; int Father[DIM];

bool bellmanFord (int startNode, int finishNode)
{
    while (!Queue.empty()) Queue.pop();
    Marked.reset(); Marked[startNode]  = 1;
    Queue.push (startNode);

    for (int i = 1; i <= nrNodes; i ++)
        Distance[i] = INF;
    Distance[startNode] = 0;

    int ok = 0;
    while (!Queue.empty())
    {
        int node = Queue.front();

        vector <int> :: iterator it;
        for (it = Edges[node].begin(); it != Edges[node].end(); it ++)
        {
            int nextNode = *it;

            if (MaxFlow[node][nextNode] < Capacity[node][nextNode])
            if (Distance[node] + Cost[node][nextNode] < Distance[nextNode])
            {
                Distance[nextNode] = Distance[node] + Cost[node][nextNode];
                Father[nextNode] = node;

                if (!Marked[nextNode])
                {
                    Queue.push(nextNode);
                    Marked[nextNode] = 1;

                    if (nextNode == finishNode)
                        ok = 1;
                }
            }
        }

        Marked[node] = 0;
        Queue.pop();
    }

    return ok;
}

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

    scanf ("%d %d", &nrNodes, &nrEdges);
    scanf ("%d %d", &startNode, &finishNode);

    for (int i = 1; i <= nrEdges; i ++)
    {
        scanf ("%d %d", &node1, &node2);
        scanf ("%d %d", &capacity, &cost);

        Capacity[node1][node2] = capacity;
        Capacity[node2][node1] = 0;
        Cost[node1][node2] =  cost;
        Cost[node2][node1] = -cost;

        Edges[node1].push_back(node2);
        Edges[node2].push_back(node1);
    }

    int flow = 0, cost = 0;
    while (bellmanFord(startNode, finishNode))
    {
        int minim = INF;

        for (int node = finishNode; node != startNode; node = Father[node])
            minim = min (minim, Capacity[Father[node]][node] - MaxFlow[Father[node]][node]);

        flow += minim;
        for (int node = finishNode; node != startNode; node = Father[node])
        {
            MaxFlow[Father[node]][node] += minim;
            MaxFlow[node][Father[node]] -= minim;

            cost += minim * Cost[Father[node]][node];
        }
    }

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

    fclose (stdin );
    fclose (stdout);

    return 0;
}