Cod sursa(job #1754345)

Utilizator HuskyezTarnu Cristian Huskyez Data 7 septembrie 2016 23:08:03
Problema Flux maxim de cost minim Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.9 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>

#define infile "fmcm.in"
#define outfile "fmcm.out"
#define inf 999999

using namespace std;

ifstream in(infile);
ofstream out(outfile);


int n, m, s, d;

int x, y, c, z;

vector<int> graph[355];

queue<int> q;

int cap[355][355];
int rez[355][355];
int cost[355][355];

int dist[355];
int parent[355];
bool vis[355];
bool r = true;

int Dijkstra(int source, int dest)
{
    //memset(dist, inf, sizeof(dist));
    for(int i=0; i<=n; i++) dist[i] = inf;

    memset(vis, false, sizeof(vis));
    memset(parent, 0, sizeof(parent));

    dist[source] = 0;
    vis[source] = true;
    for(q.push(source); !q.empty(); q.pop()){
        int node = q.front();
        for(unsigned int i=0; i<graph[node].size(); i++){
            int v = graph[node][i];
            if(cap[node][v] - rez[node][v] && dist[v] > dist[node] + cost[node][v]){
                dist[v] = dist[node] + cost[node][v];
                parent[v] = node;
                if(!vis[v]){
                    vis[v] = true;
                    q.push(v);
                }
            }
        }
    }

    int flow = inf;

    if(dist[dest] != inf){
        r = true;
        for(int x = dest; x != source; x = parent[x]){
            flow = min(flow, cap[parent[x]][x] - rez[parent[x]][x]);
        }
        for(int x = dest; x != source; x = parent[x]){
            rez[x][parent[x]] -= flow;
            rez[parent[x]][x] += flow;
        }
        return dist[dest] * flow;
    }
    return 0;
}

int main()
{
    in >> n >> m >> s >> d;

    for(int i=0; i<m; i++){
        in >> x >> y;
        in >> c >> z;
        graph[x].push_back(y);
        graph[y].push_back(x);
        cap[x][y] = c;
        cost[x][y] = z;
        cost[y][x] = -z;
    }

    int fmcm = 0;
    while(r){
        r = false;
        fmcm += Dijkstra(s, d);
    }

    out << fmcm << '\n';

    return 0;
}