Cod sursa(job #3197403)

Utilizator verde.cristian2005Verde Flaviu-Cristian verde.cristian2005 Data 26 ianuarie 2024 18:52:46
Problema Flux maxim de cost minim Scor 0
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,fakedist[351],s,d;
bool incoada[351];
int realdist[351];
int daddy[351];
int cst;
bool dijkstra()
{
    int i;
    for(i=1; i<=n; i++)
    {
        fakedist[i]=realdist[i];
        realdist[i]=1e9;
    }
    realdist[s]=0;
    priority_queue <pair<int,int> > pq;
    pq.push({0,s});
    int flow=1e9;
    incoada[s] = 1;
    while(!pq.empty())
    {
        int x=pq.top().second;
        if(incoada[x])
            continue;
        pq.pop();
        for(auto it:v[x])
            if(cap[x][it]>0&&realdist[it]>realdist[x]+cost[x][it]+fakedist[x]-fakedist[it])
            {
                realdist[it]=realdist[x]+cost[x][it]+fakedist[x]-fakedist[it];
                daddy[it]=x;
                pq.push({-realdist[it],it});
            }
    }
    for(int i = 1; i <= n; i++)
        incoada[i] = 0;
    if(realdist[d]==1e9)
        return 0;
    for(int i = 1; i <= n; i++)
        realdist[i] += fakedist[i];
    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];
    return 1;
}
void bellman()
{
    queue <int> q;
    for(int i=1; i<=n; i++)
        realdist[i]=1e9;
    realdist[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]&&realdist[it]>realdist[x]+cost[x][it])
            {
                realdist[it]=realdist[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;
    while(dijkstra()){}
    out<<cst;
    return 0;
}