Cod sursa(job #2124356)

Utilizator CrystyAngelDinu Cristian CrystyAngel Data 7 februarie 2018 09:48:21
Problema Flux maxim de cost minim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 2.33 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>

using namespace std;

#define nmax 355
#define inf 1000000000
#define mp make_pair
#define f first
#define s second

vector <int> v[nmax];
int c[nmax][nmax];
int f[nmax][nmax];
int cst[nmax][nmax];
int t[nmax];
int viz[nmax];
int d[nmax];
int used[nmax];
int n,a,b,m;

#define DIM 10000
char buff[DIM];
int poz=0;

void citeste(int &numar)
{
     numar = 0;
     char semn='+';
     while (buff[poz] < '0' || buff[poz] > '9')
     {
          semn = buff[poz];
          if (++poz == DIM)
               fread(buff,1,DIM,stdin),poz=0;
     }
     while ('0'<=buff[poz] && buff[poz]<='9')
     {
          numar = numar*10 + buff[poz] - '0';
          if (++poz == DIM)
               fread(buff,1,DIM,stdin),poz=0;
     }
     if (semn == '-')
          numar = -numar;
}

bool bf()
{
    queue <int> h;
    for(int i=1; i<=n; ++i)
        d[i]=inf;
    h.push(a);
    used[a]=1;
    d[a]=0;
    while(!h.empty())
    {
        int nod = h.front();
        h.pop();
        used[nod]=0;
        for(auto it:v[nod])
        {
            if(f[nod][it]<c[nod][it] && d[nod]+cst[nod][it]<d[it])
            {
                d[it]=d[nod]+cst[nod][it];
                t[it]=nod;
                if(!used[it])
                {
                    used[it]=1;
                    h.push(it);
                }
            }
        }
    }
    return d[b]!=inf;
}



int main()
{
    freopen("fmcm.in","r",stdin);
    freopen("fmcm.out","w",stdout);

    citeste(n);
    citeste(m);
    citeste(a);
    citeste(b);
    while(m--)
    {
        int x,y,q,z;
        citeste(x);
        citeste(y);
        citeste(q);
        citeste(z);
        c[x][y]=q;
        cst[x][y]=z;
        cst[y][x]=-z;
        v[x].push_back(y);
        v[y].push_back(x);
    }
    int ans = 0;
    while(bf())
    {
            int flow = inf;
            for(int i = b; i!=a; i=t[i])
                flow = min(flow,c[t[i]][i]-f[t[i]][i]);
            if(!flow)
                continue;
            for(int i = b; i!=a; i=t[i])
            {
                f[t[i]][i]+=flow;
                f[i][t[i]]-=flow;
                ans+=flow*cst[t[i]][i];
            }
    }
    printf("%d",ans);
}