Cod sursa(job #867588)

Utilizator visanrVisan Radu visanr Data 29 ianuarie 2013 21:01:32
Problema Cc Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.29 kb
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <queue>
#include <vector>
#include <algorithm>
using namespace std;


#define Inf 0x3f3f3f3f
#define pb push_back
#define IT vector<int> :: iterator
#define Nmax 210

int N, M, Cost[Nmax][Nmax], Father[Nmax], Dist[Nmax];
int Cap[Nmax][Nmax], Flow[Nmax][Nmax];
vector<int> G[Nmax];
bool InQueue[Nmax];
int S, D, X, Y, C;

bool BellmanFord()
{
    memset(Dist, Inf, sizeof(Dist));
    Dist[S] = 0;
    queue<int> Q; Q.push(S);
    InQueue[S] = 1;
    while(!Q.empty())
    {
        int Node = Q.front();
        Q.pop();
        InQueue[Node] = 0;
        for(IT it = G[Node].begin(); it != G[Node].end(); ++it)
            if(Cap[Node][*it] > Flow[Node][*it] && Dist[Node] + Cost[Node][*it] < Dist[*it])
            {
                Dist[*it] = Dist[Node] + Cost[Node][*it];
                Father[*it] = Node;
                if(!InQueue[*it])
                {
                    InQueue[*it] = 1;
                    Q.push(*it);
                }
            }
    }
    return (Dist[D] != Inf);
}

void MaxFlow()
{
    int Ans = 0, MinFlow;
    while(BellmanFord())
    {
        MinFlow = Inf;
        for(int Node = D; Node != S; Node = Father[Node])
            MinFlow = min(MinFlow, Cap[Father[Node]][Node] - Flow[Father[Node]][Node]);
        if(MinFlow)
        {
            for(int Node = D; Node != S; Node = Father[Node])
            {
                Flow[Father[Node]][Node] += MinFlow;
                Flow[Node][Father[Node]] -= MinFlow;
            }
            Ans += MinFlow * Dist[D];
        }
    }
    printf("%i\n", Ans);
}

int main()
{
    freopen("cc.in", "r", stdin);
    freopen("cc.out", "w", stdout);
    int i, j;
    scanf("%i", &N);
    S = 1;
    D = 2 * N + 2;
    for(i = 1; i <= N; i++)
    {
        X = i + 1;
        for(j = 1; j <= N; j++)
        {
            scanf("%i", &C);
            Y = j + N + 1;
            G[X].pb(Y);
            G[Y].pb(X);
            Cost[X][Y] = C;
            Cost[Y][X] = -C;
            Cap[X][Y] = 1;
            if(Cap[S][X] == 0) G[S].pb(X), G[X].pb(S);
            if(Cap[Y][D] == 0) G[Y].pb(D), G[D].pb(Y);
            Cap[S][X] = Cap[Y][D] = 1;
        }
    }
    MaxFlow();
    return 0;
}