Cod sursa(job #2276641)

Utilizator triscacezarTrisca Vicol Cezar triscacezar Data 5 noiembrie 2018 00:50:48
Problema Flux maxim de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.53 kb
#include <bits/stdc++.h>

const int N=360;
const int oo=2000000;

using namespace std;

ifstream f("fmcm.in");
ofstream g("fmcm.out");

int n,m,S,D,i,x,y,z,t,ans,dist[N],cap[N][N],cost[N][N];
vector<int> v[N];
priority_queue<pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > > Q;
int tata[N],d1[N],real_d[N];

void bell()
{
    queue<int> Q;
    bitset<N> in;in.reset();
    for(i=1;i<=n;i++)
        dist[i]=oo,in[i]=0;
    dist[S]=0;Q.push(S);in[S]=1;
    while(Q.size())
    {
        int x=Q.front();
        Q.pop();in[x]=0;
        for(auto it:v[x])
            if(cap[x][it]&&(dist[it]>dist[x]+cost[x][it]))
            {
                dist[it]=dist[x]+cost[x][it];
                if(!in[it])
                    Q.push(it);
                in[it]=1;
            }
    }
    return ;
}

bool dij()
{
    for(int i=1;i<=n;i++)
    {
        d1[i]=oo;
        tata[i]=0;
        real_d[i]=oo;
    }
    d1[S]=0;tata[S]=S;
    real_d[S]=0;
    Q.push({0,S});
    while(!Q.empty())
    {
        int cst=Q.top().first;
        int nod=Q.top().second;
        Q.pop();
        if(d1[nod]!=cst)
            continue;
        for(auto a:v[nod])
        {
            if(cap[nod][a])
            {
                int new_d=d1[nod]+cost[nod][a]+dist[nod]-dist[a];
                if(new_d<d1[a])
                {
                    d1[a]=new_d;
                    real_d[a]=real_d[nod]+cost[nod][a];
                    tata[a]=nod;
                    Q.push({d1[a],a});
                }
            }
        }
    }
    for(int i=1;i<=n;i++)
        dist[i]=real_d[i];
    if(d1[D]==oo)
        return false;
    int x=D;
    int flux=oo;
    while(x!=S)
    {
        flux=min(cap[tata[x]][x],flux);
        x=tata[x];
    }
    x=D;
    while(x!=S)
    {
        cap[tata[x]][x]-=flux;
        cap[x][tata[x]]+=flux;
        x=tata[x];
    }
    ans+=flux*dist[D];
    return true;
}

int main()
{
//    clock_t t;
//    t = clock();
//    cout<<((float)t)/CLOCKS_PER_SEC<<'\n';
    f>>n>>m>>S>>D;
    for(i=1;i<=m;i++)
    {
        f>>x>>y>>z>>t;
        v[x].push_back(y);
        v[y].push_back(x);
        cap[x][y]=z;
        cost[x][y]=t;
        cost[y][x]=-t;
    }
//    t = clock() - t;
//    cout<<(((float)t)/CLOCKS_PER_SEC)<<'\n';
    bell();
//    t = clock() - t;
//    cout<<(((float)t)/CLOCKS_PER_SEC)<<'\n';
    for(;dij(););
    g<<ans;
//    t = clock() - t;
//    cout<<(((float)t)/CLOCKS_PER_SEC)<<'\n';
    return 0;
}