Cod sursa(job #1409023)

Utilizator bogdanboboc97Bogdan Boboc bogdanboboc97 Data 30 martie 2015 13:01:07
Problema Flux maxim de cost minim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.76 kb
#include <fstream>
#include <vector>
#include <algorithm>
#include <queue>
#include <limits>
#define pb push_back
#define mp make_pair
#define INF numeric_limits<int>::max()
#define NM 351
using namespace std;
ifstream in("fmcm.in");
ofstream out("fmcm.out");
vector< vector<int> > a;
queue<int> q;
int n,m,s,d,flow[352][352],cap[352][352],cost[352][352],pre[352],dist[352],ct;
bool use[352];
//......................
bool bellman()
{
    for(int i=1;i<=n;i++)
    {
        pre[i]=0;
        use[i]=false;
        dist[i]=INF;
    }
    dist[s]=0;
    pre[s]=s;
    use[s]=true;
    q.push(s);
    while(!q.empty())
    {
        int x=q.front();q.pop();
        use[x]=false;
        for(vector<int>::iterator i=a[x].begin();i!=a[x].end();i++)
        if(dist[*i] > dist[x]+cost[x][*i] && cap[x][*i]-flow[x][*i] > 0)
        {
            pre[*i]=x;
            dist[*i]=dist[x]+cost[x][*i];
            if(use[*i]==false)
            {
                use[*i]=true;
                q.push(*i);
            }
        }
    }
    return pre[d];
}
//.....................
int main()
{
    in>>n>>m>>s>>d;
    a=vector< vector<int> > (n+1);
    for(;m;m--)
    {
        int x,y,z,w;
        in>>x>>y>>z>>w;
        a[x].pb(y);
        a[y].pb(x);
        cost[x][y]=w;
        cost[y][x]=-w;
        cap[x][y]=z;
    }
    //..................
    for(;bellman();)
    {
        int mx=cap[pre[d]][d]-flow[pre[d]][d];
        //.....................
        for(int x=d;pre[x]!=x;x=pre[x])
        mx=min(mx,cap[pre[x]][x]-flow[pre[x]][x]);
        //......................
        for(int x=d;pre[x]!=x;x=pre[x])
        {
            ct+=cost[pre[x]][x]*mx;
            flow[pre[x]][x]+=mx;
            flow[x][pre[x]]-=mx;
        }
    }
    out<<ct<<'\n';
    //....................
    return 0;
}