Cod sursa(job #2035119)

Utilizator tifui.alexandruTifui Ioan Alexandru tifui.alexandru Data 8 octombrie 2017 22:15:52
Problema Flux maxim de cost minim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 2.39 kb
#include <bits/stdc++.h>
#define Nmax 351
#define tip pair <int,int>
using namespace std;
ifstream f("fmcm.in");
ofstream g("fmcm.out");
list <int> G[Nmax];
int cap[Nmax][Nmax];
int cost[Nmax][Nmax];
int c_bf[Nmax];
bitset <Nmax> inq;
int dist[Nmax];
int real_d[Nmax];
int t[Nmax];
queue <int> q;
int n,s,d;
priority_queue <tip, vector <tip>, greater <tip> > pq;
bool Dijkstra()
{
    fill(dist+1,dist+n+1,INT_MAX);
    dist[s]=0;
    real_d[s]==0;
    pq.push({dist[s],s});
    int x,dij_cst,new_dist;
    list <int> :: iterator it;
    while(!pq.empty())
    {
        x=pq.top().second;
        dij_cst=pq.top().first;
        pq.pop();
        if(dist[x]==dij_cst)
        for(it=G[x].begin();it!=G[x].end();it++)
        if(cap[x][*it])
        {
            new_dist=dist[x]+cost[x][*it]+c_bf[x]-c_bf[*it];
            if(new_dist<dist[*it])
            {
                dist[*it]=new_dist;
                real_d[*it]=real_d[x]+cost[x][*it];
                t[*it]=x;
                pq.push({dist[*it],*it});
            }
        }
    }
    memcpy(c_bf,real_d,sizeof(dist));
    return dist[d]!=INT_MAX;
}
void BF()
{
    fill(c_bf+1,c_bf+n+1,INT_MAX);
    c_bf[s]=0;
    q.push(s);
    inq[s]=true;
    int x;
    list <int> :: iterator it;
    while(!q.empty())
    {
        x=q.front();
        q.pop();
        inq[x]=false;
        for(it=G[x].begin();it!=G[x].end();it++)
            if(cap[x][*it] and c_bf[*it]>c_bf[x]+cost[x][*it])
            {
                c_bf[*it]=c_bf[x]+cost[x][*it];
                if(!inq[*it])
                {
                    q.push(*it);
                    inq[*it]=true;
                }
            }
    }
}
int main()
{
    int m,i,j,z,cst,k;
    f>>n>>m>>s>>d;
    for(k=1;k<=m;k++)
    {
        f>>i>>j>>z>>cst;
        G[i].push_back(j);
        G[j].push_back(i);
        cap[i][j]=z;
        cost[i][j]=cst;
        cost[j][i]=-cst;
    }
    BF();
    int ans=0,minn,x;
    while(Dijkstra())
    {
        minn=INT_MAX;
        x=d;
        while(x!=s)
        {
            if(cap[t[x]][x]<minn)
                minn=cap[t[x]][x];
            x=t[x];
        }
        ans+=(minn*real_d[d]);
        x=d;
        while(x!=s)
        {
            cap[t[x]][x]-=minn;
            cap[x][t[x]]+=minn;
            x=t[x];
        }
    }
    g<<ans;


    return 0;
}