Cod sursa(job #2900943)

Utilizator verde.cristian2005Verde Flaviu-Cristian verde.cristian2005 Data 12 mai 2022 16:30:14
Problema Flux maxim de cost minim Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.21 kb
#include <bits/stdc++.h>
using namespace std;
ifstream in("fmcm.in");
ofstream out("fmcm.out");
vector <int> v[351];
int cap[351][351],cost[351][351],n,dist[351],s,d;
bool incoada[351];
int realdist[351],fakedist[351];
int daddy[351];
priority_queue <pair<int,int> > pq;
pair <int,int> dijkstra()
{
    int D=dist[d];
    int i;
    for(i=1; i<=n; i++)
    {
        fakedist[i]=dist[i];
        realdist[i]=1e9;
    }
    realdist[s]=dist[s]=0;
    pq.push({0,s});
    int cst=0,flow=1e9;
    while(!pq.empty())
    {
        int x=pq.top().second;
        pq.pop();
        for(auto it:v[x])
            if(cap[x][it]&&realdist[it]>realdist[x]+cost[x][it]+fakedist[x]-fakedist[it])
            {
                realdist[it]=realdist[x]+cost[x][it]+fakedist[x]-fakedist[it];
                dist[it]=dist[x]+cost[x][it];
                daddy[it]=x;
                pq.push({-realdist[it],it});
            }
    }
    if(realdist[d]==1e9)
        return {0,0};
    for(i=d; i!=s; i=daddy[i])
        flow=min(flow,cap[daddy[i]][i]);
    for(i=d; i!=s; i=daddy[i])
    {
        cap[daddy[i]][i]-=flow;
        cap[i][daddy[i]]+=flow;
    }
    cst=flow*(realdist[d]+D);
    return {flow,cst};
}
queue <int> q;
void bellman()
{
    for(int i=1; i<=n; i++)
        dist[i]=1e9;
    dist[s]=0;
    q.push(s);
    incoada[s]=1;
    while(!q.empty())
    {
        int x=q.front();
        incoada[x]=0;
        q.pop();
        for(auto it:v[x])
            if(cap[x][it]&&dist[it]>dist[x]+cost[x][it])
            {
                dist[it]=dist[x]+cost[x][it];
                if(!incoada[it])
                {
                    incoada[it]=1;
                    q.push(it);
                }
            }
    }
}
int main()
{
    int m,i,a,b,c,k;
    in>>n>>m>>s>>d;
    for(i=1; i<=m; i++)
    {
        in>>a>>b>>c>>k;
        cost[a][b]=k;
        cost[b][a]=-k;
        cap[a][b]=c;
        v[a].push_back(b);
        v[b].push_back(a);
    }
    bellman();
    pair <int,int> x;
    int cost=0,flow=0;
    do
    {
        x=dijkstra();
        flow+=x.first;
        cost+=x.second;
    }
    while(x!= make_pair(0,0));
    out<<cost;
    return 0;
}