Cod sursa(job #2969950)

Utilizator RobertlelRobert Robertlel Data 23 ianuarie 2023 21:50:13
Problema Flux maxim de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.83 kb
#include <bits/stdc++.h>
using namespace std;

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

int n , m , source , dest;

vector <int> v[355] , dist;
vector <int> tata;
vector <bool>viz;


int cap[355][355] , cost[355][355] ;

int dij (int start , int stop)
{
    viz.assign (n + 1 , 0);
    dist.assign (n + 1 , INT_MAX);
    queue < int > coada;
    coada.push (start);
    viz[start] = 1;
    dist[start] = 0;
    tata[start] = start;
    while (!coada.empty())
    {
        int nod = coada.front ();
        coada.pop ();
        viz[nod] = 0;
        for (auto vecin : v[nod])
        {
            if (cap[nod][vecin] > 0 && dist[vecin] > dist[nod] + cost[nod][vecin])
            {
                dist[vecin] = dist[nod] + cost[nod][vecin];
                tata[vecin] = nod;
                if (viz[vecin] == 0)
                {
                    coada.push (vecin);
                    viz[vecin] = 1;
                }
            }
        }
    }
    return dist[stop];
}
int main()
{
    int x , y , a , b;
    f >> n >> m >> source >> dest;
    for (int i = 1 ; i <= m ; i++)
    {
        f >> x >> y >> a >> b;
        v[x].push_back (y);
        v[y].push_back (x);
        cap[x][y] = a;
        cost[x][y] = b;
        cost[y][x] = -b;
    }
    tata.assign (n + 1 , 0);
    int maxflow = 0;

    while (true)
    {
        int suma = dij (source , dest);

        if (suma == INT_MAX)
            break;

        int flow = INT_MAX;

        for (int j = dest ; j != source ; j = tata[j])
            flow = min (flow , cap[tata[j]][j]);

        for (int j = dest ; j != source ; j = tata[j])
        {
            cap[tata[j]][j] -= flow;
            cap[j][tata[j]] += flow;
        }
        maxflow += flow * suma;
    }
    g << maxflow;
    return 0;
}