Cod sursa(job #2393975)

Utilizator andrei32576Andrei Florea andrei32576 Data 1 aprilie 2019 11:26:56
Problema Flux maxim de cost minim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.83 kb
#include <bits/stdc++.h>
using namespace std;

#define nmax 352
#define inf 2000000000

int n, m, S, D, i, x, y, cap, ct, drum;
int d[nmax], t[nmax], c[nmax][nmax], F[nmax][nmax], viz[nmax];

struct muchie
{
    int x, c;
};

vector <muchie> G[nmax];
queue <int> q;

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

long long BellmanFord()
{
    for (int i=1;i<=n;i++)
    {
        d[i] = inf;
        t[i] = -1;
    }

    while (!q.empty())
        q.pop();
    memset(viz, 0, sizeof(viz));
    d[S] = 0;
    q.push(S);
    viz[S] = 1;

    while (!q.empty())
    {
        int nod = q.front();
        q.pop();
        for (auto &it : G[nod])
        {
            if (F[nod][it.x] < c[nod][it.x] && d[nod] + it.c < d[it.x])
            {
                d[it.x] = d[nod] + it.c;
                t[it.x] = nod;
                if (!viz[it.x])
                {
                    viz[it.x] = 1;
                    q.push(it.x);
                }
            }
        }

        viz[nod] = 0;
    }

    if (d[D] != inf)
    {
        drum = 1;
        int fm = inf;
        for (int nod = D; nod != S; nod = t[nod])
            fm = min(fm, c[t[nod]][nod] - F[t[nod]][nod]);
        for (int nod = D; nod != S; nod = t[nod])
        {
            F[t[nod]][nod] += fm;
            F[nod][t[nod]] -= fm;
        }

        return fm * d[D];
    }

    return 0;
}

long long Flux()
{
    long long rez = 0;
    drum = 1;
    while (drum)
    {
        drum = 0;
        rez += BellmanFord();
    }

    return rez;
}

int main()
{
    f>>n>>m>>S>>D;
    for (i=1;i<=m;i++)
    {
        f>>x>>y>>cap>>ct;
        c[x][y] = cap;
        G[x].push_back({y, ct});
        G[y].push_back({x, -ct});
    }

    g<<Flux();

    f.close();
    g.close();
    return 0;
}