Cod sursa(job #1502826)

Utilizator stefanzzzStefan Popa stefanzzz Data 15 octombrie 2015 00:33:13
Problema Flux maxim de cost minim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.66 kb
#include <stdio.h>
#include <vector>
#include <queue>
#define INF 2000000000
#define MAXN 400
#define MIN(a, b) (((a) < (b))?(a):(b))
using namespace std;

int n, m, start, fin, fx[MAXN][MAXN], cap[MAXN][MAXN], cost[MAXN][MAXN];
int x, y, c, z, dist[MAXN], bk[MAXN];
bool uzq[MAXN];
vector<int> G[MAXN];

bool BelmanFord() {
    for(int i = 1; i <= n; i++) {
        dist[i] = INF;
        bk[i] = uzq[i] = 0;
    }
    dist[start] = 0;

    queue<int> q;
    q.push(start);
    uzq[start] = 1;

    while(!q.empty()) {
        int x = q.front();
        q.pop(), uzq[x] = 0;

        for(auto y: G[x])
            if(fx[x][y] < cap[x][y] && dist[x] + cost[x][y] < dist[y]) {
                dist[y] = dist[x] + cost[x][y];
                bk[y] = x;
                if(!uzq[y]) q.push(y), uzq[y] = 1;
            }
    }

    return bk[fin];
}

int main()
{
    freopen("fmcm.in", "r", stdin);
    freopen("fmcm.out", "w", stdout);

    scanf("%d %d %d %d", &n, &m, &start, &fin);
    for(int i = 1; i <= m; i++) {
        scanf("%d %d %d %d", &x, &y, &c, &z);
        cap[x][y] = c;
        cost[x][y] = z;
        cost[y][x] = -z;
        G[x].push_back(y);
        G[y].push_back(x);
    }

    int sol = 0;
    while(BelmanFord()) {
        int x = fin, flow = INF;
        while(x != start) {
            flow = MIN(flow, cap[bk[x]][x] - fx[bk[x]][x]);
            x = bk[x];
        }
        x = fin;
        while(x != start) {
            fx[bk[x]][x] += flow;
            fx[x][bk[x]] -= flow;
            sol += flow * cost[bk[x]][x];
            x = bk[x];
        }
    }

    printf("%d\n", sol);

    return 0;
}