Cod sursa(job #2737389)

Utilizator AndreiD31Dragan Andrei AndreiD31 Data 4 aprilie 2021 18:33:05
Problema Flux maxim de cost minim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.73 kb
#include <bits/stdc++.h>

using namespace std;

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

queue<int>q;
priority_queue < pair < int , int > , vector < pair < int , int > > , greater < pair < int , int > > > h;
int s,d,n,max_flow,inCoada[355],tata[355],cost_bell[355],cost_dijk[355],new_cost_bell[355],C[355][355],flux[355][355],cost[355][355];
vector<int>v[355];

void Bellman()
{
    for(int i=1;i<=n;i++)cost_bell[i]=INT_MAX/2;
    cost_bell[s]=0;q.push(s);inCoada[s]=1;
    while(!q.empty())
    {
        int nod=q.front();
        q.pop();inCoada[nod]=0;
        for(int i=0;i<v[nod].size();i++)
        {
            int vecin=v[nod][i];
            int cost_intre=cost[nod][vecin];
            if(cost_bell[vecin]>cost_bell[nod]+cost_intre && flux[nod][vecin]<C[nod][vecin])
            {
                cost_bell[vecin]=cost_bell[nod]+cost_intre;
                if(inCoada[vecin]==0)
                {
                    inCoada[vecin]=1;
                    q.push(vecin);
                }
            }
        }
    }
}

int Dijkstra()
{
    for(int i=1;i<=n;i++)cost_dijk[i]=INT_MAX/2,new_cost_bell[i]=INT_MAX/2,tata[i]=0;
    cost_dijk[s]=0;h.push({0,s});new_cost_bell[s]=0;
    while(!h.empty())
    {
        int nod=h.top().second;
        int cst=h.top().first;
        h.pop();
        if(cst==cost_dijk[nod])
        {

            for(int i=0;i<v[nod].size();i++)
            {
                int vecin=v[nod][i];
                int cost_intre=cost[nod][vecin]+cost_bell[nod]-cost_bell[vecin];
                if(cost_dijk[vecin]>cost_dijk[nod]+cost_intre && flux[nod][vecin]<C[nod][vecin])
                {
                    cost_dijk[vecin]=cost_dijk[nod]+cost_intre;
                    h.push({cost_dijk[vecin],vecin});
                    new_cost_bell[vecin]=new_cost_bell[nod]+cost[nod][vecin];
                    tata[vecin]=nod;
                }
            }
        }
    }

    if(cost_dijk[d]==INT_MAX/2)return 0;

    int nod,flux_min=INT_MAX;
    nod=d;
    while(tata[nod]!=0)
    {
        flux_min=min(flux_min,C[tata[nod]][nod]-flux[tata[nod]][nod]);
        nod=tata[nod];
    }

    max_flow+=flux_min*new_cost_bell[d];

    nod=d;
    while(tata[nod]!=0)
    {
        flux[tata[nod]][nod]+=flux_min;
        flux[nod][tata[nod]]-=flux_min;
        nod=tata[nod];
    }

    for(int i=1;i<=n;i++)cost_bell[i]=new_cost_bell[i];
    return 1;
}

int m,i,x,y,c,z;
int main()
{
    f>>n>>m>>s>>d;
    for(i=1;i<=m;i++)
    {
        f>>x>>y>>c>>z;
        v[x].push_back(y);
        v[y].push_back(x);
        C[x][y]=c;
        cost[x][y]=z;cost[y][x]=-z;
    }

    Bellman();
    while(Dijkstra());
    g<<max_flow;
    return 0;
}