Cod sursa(job #2988701)

Utilizator velciu_ilincavelciu ilinca velciu_ilinca Data 5 martie 2023 13:00:17
Problema Flux maxim de cost minim Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.73 kb
#include <fstream>
#include <iostream>
#include <vector>
#include <queue>
#include <cstring>
using namespace std;
ifstream in("fmcm.in");
ofstream out("fmcm.out");
const int nmax = 1001;
const int INF = 0x3f3f3f3f;
vector<int>g[nmax+1];

int capacity[nmax+1][nmax+1];
int flow[nmax+1][nmax+1];
int dist[nmax+1];
int tata[nmax+1];
int cost[nmax+1][nmax+1];
int viz[nmax+1];
int n,m;
int s,d;
struct muchie
{
    int inc,sf;
};
vector<muchie>muchii;
int bellman_ford(int start,int dest)
{
    memset(dist, INF, sizeof dist);
    memset(tata, 0, sizeof tata);

    dist[start] = 0;
    tata[start] = start;
    for(int i = 1; i < n; i++)
        for(int j = 0; j < muchii.size(); j++)
        {
            muchie newmuchie = muchii[j];
            int newdist = dist[newmuchie.inc]+cost[newmuchie.inc][newmuchie.sf];
            int newcapacity = capacity[newmuchie.inc][newmuchie.sf]-flow[newmuchie.inc][newmuchie.sf];
            if(dist[newmuchie.inc] != INF && dist[newmuchie.sf]>newdist && newcapacity > 0)
            {
                dist[newmuchie.sf] = newdist;
                tata[newmuchie.sf] = newmuchie.inc;
            }
        }
    return dist[dest];
}
int find_muchie_min()
{
    int node = d;
    int muchiemin = 1e9;
    while(tata[node] != node)
    {
        int parent = tata[node];
        muchiemin = min(muchiemin, capacity[parent][node] - flow[parent][node]);
        node = parent;
    }
    return muchiemin;
}
void updateflow(int muchiemin)
{
    int node = d;
    while (tata[node] != node)
    {
        int parent = tata[node];
        flow[parent][node] += muchiemin;
        flow[node][parent] -= muchiemin;
        node = parent;
    }
}
int main()
{
    in>>n>>m>>s>>d;
    for(int i=1; i<=m; i++)
    {
        int x,y,capacitate,price;
        in>>x>>y>>capacitate>>price;
        g[x].push_back(y);
        g[y].push_back(x);
        capacity[x][y] = capacitate;
        cost[x][y] = price;
        cost[y][x] = -price;//ca sa ma pot intoarce => cost 5 dus si ma intorc =>5-5=0..ca si cum nu as fi mers pe acel drum

        muchie m;

        m.inc = x;
        m.sf = y;
        muchii.push_back(m);

        m.inc = y;
        m.sf = x;
        muchii.push_back(m);
    }
    int ans = 0;
    int costmin = bellman_ford(s,d);
    while(costmin != INF)
    {
        //cout << "after bellman" << endl;
        int muchiemin = find_muchie_min();//!!!
        //cout << "after findmin" << endl;
        updateflow(muchiemin);
        //cout << "after update" << endl;
        ans += (muchiemin * costmin);
        cout << ans << ' '<<' '<<costmin<<' '<<muchiemin<<'\n';
        costmin = bellman_ford(s,d);
    }

    out<<ans;
    return 0;
}