Cod sursa(job #2875849)

Utilizator BAlexandruBorgovan Alexandru BAlexandru Data 22 martie 2022 13:59:06
Problema Flux maxim de cost minim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.8 kb
#include <fstream>
#include <vector>

using namespace std;

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

const int INF = 2e9;

int n, m, s, d;

int dist[351];
int parent[351];

int cap[351][351];
int cost[351][351];
int flow[351][351];

vector < int > adj[351];

int bellmanFord(int source, int dest)
{
    for (int i = 1; i <= n; i++)
    {
        dist[i] = INF;
        parent[i] = 0;
    }

    dist[source] = 0;

    bool stop = false;

    while (!stop)
    {
        stop = true;

        for (int i = 1; i <= n; i++)
            for (auto it : adj[i])
                if (cap[i][it] - flow[i][it] > 0 && dist[i] + cost[i][it] < dist[it])
                {
                    dist[it] = dist[i] + cost[i][it];
                    parent[it] = i;
                    stop = false;
                }
    }

    if (dist[dest] != INF)
    {
        int fmin = INF;

        for (int i = dest; i != source; i = parent[i])
            fmin = min(fmin, cap[parent[i]][i] - flow[parent[i]][i]);

        for (int i = dest; i != source; i = parent[i])
        {
            flow[parent[i]][i] += fmin;
            flow[i][parent[i]] -= fmin;
        }

        return fmin * dist[dest];
    }

    return 0;
}

int main()
{
    f >> n >> m >> s >> d;

    for (int i = 1; i <= m; i++)
    {
        int x, y, c, z; f >> x >> y >> c >> z;

        adj[x].push_back(y);
        adj[y].push_back(x);

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

    long long ans = 0;
    bool stop = false;

    while (!stop)
    {
        int aux = bellmanFord(s, d);

        g << aux << " " << ans << "\n";

        ans += aux;

        if (!aux)
            stop = true;
    }

    g << ans << "\n";

    return 0;
}