Cod sursa(job #2957676)

Utilizator EduardSanduSandu Eduard Alexandru EduardSandu Data 23 decembrie 2022 12:10:13
Problema Flux maxim de cost minim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.89 kb
#include <bits/stdc++.h>
using namespace std;

ifstream fin("fmcm.in");
ofstream fout("fmcm.out");

int capacity[400][400],cost[400][400],n,m,flow,src,dest;
long long max_cost;
vector<int> cst;
vector<int> visited,parent;
vector<vector<int>> v;

void bfs()
{
    fill(parent.begin(), parent.end(), 0);
    fill(cst.begin(), cst.end(), INT_MAX);

    parent[src] = 0;
    cst[src] = 0;
    queue<int> q;
    q.push(src);

    while(!q.empty())
    {
        int nod = q.front();

        q.pop();

        visited[nod] = false;

        for(int i=0; i<v[nod].size(); i++)
        {
            if(capacity[nod][v[nod][i]] > 0 && cst[nod] + cost[nod][v[nod][i]] < cst[v[nod][i]])
            {
                parent[v[nod][i]] = nod;
                cst[v[nod][i]] = cst[nod] + cost[nod][v[nod][i]];
                if(!visited[v[nod][i]]){
                    q.push(v[nod][i]);
                    visited[v[nod][i]];
                }


            }
        }
    }
}

int main()
{
    int a,b,c,d;
    fin>>n>>m>>src>>dest;
    visited.resize(n+2, 0);
    parent.resize(n+2, 0);
    cst.resize(n+2, 0);
    v.resize(n+2, {});

    for(int i=1; i<=m; i++)
    {
        fin>>b>>c>>a>>d;
        v[b].push_back(c);
        v[c].push_back(b);
        capacity[b][c] = a;
        cost[b][c] = d;
        cost[c][b] = -d;
    }

    bfs();

    while(cst[dest] < INT_MAX)
    {
                flow = INT_MAX;
                for(int j=dest; j!=src; j=parent[j])
                {
                    flow=min(flow, capacity[parent[j]][j]);
                }
                for(int j=dest; j!=src; j=parent[j])
                {
                    capacity[parent[j]][j] -= flow;
                    capacity[j][parent[j]] += flow;
                }
                max_cost += flow * cst[dest];
        bfs();
    }
    fout<<max_cost;
    return 0;
}