Cod sursa(job #1657790)

Utilizator tudormaximTudor Maxim tudormaxim Data 20 martie 2016 20:03:21
Problema Flux maxim de cost minim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 2.1 kb
#include <algorithm>
#include <iostream>
#include <fstream>
#include <bitset>
#include <vector>
#include <queue>
using namespace std;

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

const int nmax = 355;
const int oo = (1<<30);
vector <pair<int,int> > g[nmax];
int c[nmax][nmax], f[nmax][nmax], dady[nmax], dist[nmax], n, m;

inline bool bellman(int source, int dest)
{
    vector <pair<int,int> > :: iterator it;
    queue <int> q;
    bitset <nmax> viz=0;
    int dad, son, cost;
    fill(dist+1, dist+n+1, oo);
    dist[source]=0;
    q.push(source);
    while(!q.empty())
    {
        dad=q.front();
        viz[dad]=false;
        q.pop();
        for(it=g[dad].begin(); it!=g[dad].end(); it++)
        {
            son=it->first;
            cost=it->second;
            if(dist[son] > dist[dad]+cost && c[dad][son] > f[dad][son])
            {
                dist[son]=dist[dad]+cost;
                dady[son]=dad;
                if(viz[son]==false && son!=dest)
                {
                    viz[son]=true;
                    q.push(son);
                }
            }
        }
    }
    if(dist[dest]==oo) return false;
    return true;
}

void Edmunson_Karp(int source, int dest)
{
    vector <pair<int,int> > :: iterator it;
    int node, maxflow=0, flow;
    while(bellman(source, dest))
    {
        flow=oo;
        for(node=dest; node!=source; node=dady[node])
            flow=min(flow, c[dady[node]][node]-f[dady[node]][node]);

        maxflow+=flow*dist[dest];
        for(node=dest; node!=source; node=dady[node])
        {
            f[dady[node]][node]+=flow;
            f[node][dady[node]]-=flow;
        }
    }
    fout << maxflow;
}

int main()
{
    ios_base::sync_with_stdio(false);
    int x, y, cap, cost, i, source, dest;
    fin >> n >> m >> source >> dest;
    for(i=1; i<=m; i++)
    {
        fin >> x >> y >> cap >> cost;
        g[x].push_back({y, cost});
        g[y].push_back({x, -cost});
        c[x][y]=cap;
    }
    Edmunson_Karp(source, dest);
    fin.close();
    fout.close();
    return 0;
}