Cod sursa(job #1223396)

Utilizator mihai995mihai995 mihai995 Data 28 august 2014 04:51:59
Problema Flux maxim de cost minim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.97 kb
#include <fstream>
#include <cstring>
#include <vector>
#include <queue>
using namespace std;

const int N = 601, QSize = (1 << 10) - 1, inf = 0x3f3f3f3f;

class Queue{
    int v[QSize + 1], st, dr;
    bool use[N];

public:
    Queue(){
        st = dr = 0;
    }

    inline void push(int x){
        if (!use[x]){
            v[dr] = x;
            use[x] = true;
            dr = (dr + 1) & QSize;
        }
    }

    inline int pop(){
        int x = v[st];
        st = (st + 1) & QSize;
        use[x] = false;
        return x;
    }

    inline bool isEmpty(){
        return st == dr;
    }
};

struct Edge{
    int y, c;

    Edge(int y, int c) :
        y(y),
        c(c)
    {}
};

vector<Edge> graph[N];
int cf[N][N], dist[N], T[N], n;
bool isEdge[N][N];
Queue Q;

inline void relax(int x, int y, int F){
    cf[x][y] -= F;
    cf[y][x] += F;
}

bool bellmaxFord(int x, int D){
    memset(dist, inf, sizeof(dist));
    memset(T, 0, sizeof(T));
    dist[x] = 0;
    Q.push(x);

    while ( !Q.isEmpty() ){
        x = Q.pop();

        for (Edge E : graph[x])
            if ( cf[x][E.y] && dist[x] + E.c < dist[E.y]){
                dist[E.y] = dist[x] + E.c;
                Q.push(E.y);
                T[E.y] = x;
            }
    }

    return dist[D] != inf;
}

int maxFlow(int S, int D){
    int flow = 0, cost = 0;
    while ( bellmaxFord(S, D) ){
        int F = inf;
        for (int i = D ; i != S ; i = T[i])
            F = min(F, cf[ T[i] ][i]);
        for (int i = D ; i != S ; i = T[i])
            relax(T[i], i, F);

        cost += F * dist[D];
        flow += F;
    }
    return cost;
}

int main(){
    ifstream in("fmcm.in");
    int m, x, y, cap, cost, S, D;

    in >> n >> m >> S >> D;
    while (m--){
        in >> x >> y >> cap >> cost;

        cf[x][y] = cap;
        graph[x].push_back( Edge(y, cost) );
        graph[y].push_back( Edge(x, -cost) );
    }

    in.close();

    ofstream out("fmcm.out");
    out << maxFlow(S, D) << '\n';
    out.close();

    return 0;
}