Cod sursa(job #1626987)

Utilizator radarobertRada Robert Gabriel radarobert Data 3 martie 2016 13:24:37
Problema Flux maxim de cost minim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.83 kb
#include <fstream>
#include <vector>
#include <algorithm>

using namespace std;

const int INF = 0x3f3f3f3f;
vector<int> g[352];
int cost[352][352], c[352][352], f[352][352];
int q[1000000], d[352], father[352];
bool in_queue[352];
int sol = 0;

bool bellmanFord(int n, int source, int sink)
{
    for (int i = 1; i <= n; i++)
        d[i] = INF;
    d[source] = 0;
    int qsize = 1;
    q[1] = source;
    in_queue[source] = true;

    for (int i = 1; i <= qsize; i++)
    {
        int node = q[i];
        in_queue[node] = false;
        for (unsigned j = 0; j < g[node].size(); j++)
            if (c[node][g[node][j]] - f[node][g[node][j]] > 0 && d[g[node][j]] > d[node] + cost[node][g[node][j]])
            {
                d[g[node][j]] = d[node] + cost[node][g[node][j]];
                father[g[node][j]] = node;
                if (!in_queue[g[node][j]])
                {
                    q[++qsize] = g[node][j];
                    in_queue[g[node][j]] = true;
                }
            }
    }

    if (d[sink] == INF)
        return false;

    int fmax = INF;
    for (int i = sink; i != source; i = father[i])
        fmax = min(fmax, c[father[i]][i] - f[father[i]][i]);
    for (int i = sink; i != source; i = father[i])
    {
        f[father[i]][i] += fmax;
        f[i][father[i]] -= fmax;
    }
    sol += fmax * d[sink];

    return true;
}

int main()
{
    ifstream in("fmcm.in");
    ofstream out("fmcm.out");

    int n, m, source, sink;
    in >> n >> m >> source >> sink;
    for (int i = 1, x, y; i <= m; i++)
    {
        in >> x >> y;
        in >> c[x][y] >> cost[x][y];
        cost[y][x] = -cost[x][y];
        g[x].push_back(y);
        g[y].push_back(x);
    }

    while(bellmanFord(n, source, sink));

    out << sol << '\n';

    return 0;
}