Cod sursa(job #1871444)

Utilizator borcanirobertBorcani Robert borcanirobert Data 7 februarie 2017 13:25:50
Problema Cc Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.04 kb
#include <fstream>
#include <iostream>
#include <vector>
#include <queue>
using namespace std;

ifstream fin("cc.in");
ofstream fout("cc.out");

using VI = vector<int>;
struct Nod{
    int nod, cost;

    bool operator < ( const Nod& a ) const
    {
        return cost > a.cost;
    }
};
const int MAX = 2*105;
const int Inf = 0x3f3f3f3f;
vector<int> G[MAX];
int n, N;
VI P;
int C[MAX][MAX];
int F[MAX][MAX];
int m[MAX][MAX];
int dist_min;

void ReadAndBuildGraph();
bool Bellman_Ford();
void Write();

int main()
{
    ReadAndBuildGraph();
    while ( Bellman_Ford() );

    fout << dist_min << '\n';

    fin.close();
    fout.close();
    return 0;
}

void ReadAndBuildGraph()
{
    int x;
    fin >> n; N = 2*n + 1;
    for ( int i = 1; i <= n; ++i )
        for ( int j = 1; j <= n; ++j )
        {
            fin >> x;
            G[i].push_back(n + j);
            G[n + j].push_back(i);

            C[i][n + j] = 1;

            m[i][n + j] = x;
            m[n + j][i] = -x;
        }

    for ( int i = 1; i <= n; ++i )
    {
        G[0].push_back(i);
        G[i].push_back(0);

        C[0][i] = 1;
    }

    for ( int i = n + 1; i < N; ++i )
    {
        G[i].push_back(N);
        G[N].push_back(i);

        C[i][N] = 1;
    }
}

bool Bellman_Ford()
{
    queue<int> Q;
    P = VI(N + 1, Inf);
    VI t(N + 1);

    P[0] = 0;
    Q.push(0);

    while ( !Q.empty() )
    {
        int x = Q.front();
        Q.pop();

        for ( const auto& y : G[x] )
            if ( C[x][y] - F[x][y] > 0 )
            {
                int c_nou = P[x] + m[x][y];
                if ( c_nou >= P[y] ) continue;

                P[y] = c_nou;
                t[y] = x;
                Q.push(y);
            }
    }

    if ( P[N] >= Inf ) return false;
    dist_min += P[N];

    for ( int i = N; i != 0; i = t[i] )
    {
        F[t[i]][i]++;
        F[i][t[i]]--;
    }

  /*  for ( int i = 1; i <= N; ++i )
        cout << P[i] << ' ';
    cin.get();  */
}