Cod sursa(job #3225791)

Utilizator Alex_Mihai10Mihai Alex-Ioan Alex_Mihai10 Data 18 aprilie 2024 20:31:08
Problema Flux maxim de cost minim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.66 kb
#include <bits/stdc++.h>
#define MAX 355

using namespace std;

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

int cost[MAX][MAX],flux[MAX][MAX],cap[MAX][MAX];
vector<int>vec[MAX];
int n,m,s,d;
int tata[MAX];
int dist[MAX];
int rasp;

bool bellmanford()
{
    int i;
    for(i=1;i<=n;++i)
        dist[i]=1e9;
    dist[s]=0;
    queue<int>q;
    bitset<MAX>inq;
    q.push(s);
    while(!q.empty())
    {
        int nod=q.front();
        q.pop();
        inq[nod]=0;
        for(i=0;i<vec[nod].size();++i)
        {
            int vc=vec[nod][i];
            if(cap[nod][vc]>flux[nod][vc] && dist[vc]>dist[nod]+cost[nod][vc])
            {
                dist[vc]=dist[nod]+cost[nod][vc];
                tata[vc]=nod;
                if(!inq[vc])
                {
                    q.push(vc);
                    inq[vc]=1;
                }
            }
        }
    }
    if(dist[d]<1e9)
    {
        int nod=d;
        int minn=1e9;
        while(nod!=s)
        {
            minn=min(minn,cap[tata[nod]][nod]-flux[tata[nod]][nod]);
            nod=tata[nod];
        }
        nod=d;
        while(nod!=s)
        {
            flux[tata[nod]][nod]+=minn;
            flux[nod][tata[nod]]-=minn;
            nod=tata[nod];
        }
        rasp+=minn*dist[d];
        return 1;
    }
    return 0;
}

int main()
{
    fin>>n>>m>>s>>d;
    while(m--)
    {
        int x,y,c,z;
        fin>>x>>y>>c>>z;
        vec[x].push_back(y);
        vec[y].push_back(x);
        cap[x][y]=c;
        cost[x][y]=z;
        cost[y][x]=-z;
    }
    while(bellmanford());
    fout<<rasp;
    return 0;
}