Cod sursa(job #988827)

Utilizator danalex97Dan H Alexandru danalex97 Data 23 august 2013 22:47:46
Problema Flux maxim de cost minim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 2.5 kb
#include <algorithm>
#include <fstream>
#include <vector>
#include <cstring>
#include <queue>
using namespace std;

typedef struct { int x,c; } node;

struct cmp_node
{
    bool operator () (node x,node y)
    {
        return x.c > y.c;
    }
};

node make_node(int x,int c)
{
    node now;
    now.x = x;
    now.c = c;
    return now;
}

typedef priority_queue<node,vector<node>,cmp_node> MinH;

ifstream F("fmcm.in");
ofstream G("fmcm.out");

const int Nmax = 355;
const int Mmax = 12510;
const int value = 1010;

int N,M,D[Nmax];
int capacity[Nmax][Nmax];
int cost[Nmax][Nmax];
vector<int> V[Nmax];
int last[Nmax];
int total_flow,total_cost;

#define IT(type) vector<type>::iterator

int Bellman_pq(int start,int target)
{
    MinH Q;
    memset(last,0,sizeof(last));
    memset(D,0x3f,sizeof(D));

    D[start] = 0;
    last[start] = -1;
    Q.push( make_node(start,D[start]) );

    while ( Q.size() )
    {
        node now = Q.top();
        Q.pop();

        if ( D[now.x] != now.c )
            continue;

        for (IT(int) it=V[now.x].begin();it!=V[now.x].end();++it)
            if ( capacity[now.x][*it] != 0 )
                if ( D[*it] > D[now.x] + cost[now.x][*it] )
                {
                    D[*it] = D[now.x] + cost[now.x][*it];
                    last[*it] = now.x;
                    Q.push( make_node( *it , D[now.x] + cost[now.x][*it] ) );
                }
    }

    return D[target] != D[0];
}

int main()
{
    F>>N>>M;
    int source = 1;
    int target = N;
    F>>source>>target;
    for (int i=1,x,y,c,cc;i<=M;++i)
    {
        F>>x>>y>>c>>cc;
        if ( capacity[x][y] == 0 && capacity[y][x] == 0 )
        {
            V[ x ].push_back( y );
            V[ y ].push_back( x );
        }
        capacity[x][y] += c;
        cost[x][y] = cc;
        cost[y][x] = -cc;
    }

    while ( Bellman_pq(source,target) != 0 )
    {
        int Cmin = capacity[last[target]][target];
        for (int now=last[target];now!=source;now=last[now])
            Cmin = min( Cmin , capacity[last[now]][now] );

        total_flow += Cmin;

        for (int now=last[target];now!=source;now=last[now])
        {
            capacity[last[now]][now] -= Cmin;
            capacity[now][last[now]] += Cmin;
            total_cost += cost[last[now]][now] * Cmin;
        }
        capacity[last[target]][target] -= Cmin;
        total_cost += cost[last[target]][target] * Cmin;
    }

    G<<total_cost<<'\n';
}