Cod sursa(job #2602187)

Utilizator Anakin1001George Giorgiu Gica Anakin1001 Data 16 aprilie 2020 10:15:16
Problema Cc Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.16 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

ifstream f ( "cc.in" );
ofstream g ( "cc.out" );

const int N = 351;
const int inf = 125000000;
vector < int > graph[N];
queue < int > q;
int C[N][N], F[N][N], d[N], tata[N], cost[N][N];
int S, D, n;
bool viz[N];

bool bfs ( int start ){
    for ( int i = 1; i <= 2 * n + 1; i++ ){
        viz[i] = tata[i] = 0;
        d[i] = inf;
    }
    d[start] = 0;
    viz[start] = 1;
    q.push ( start );
    while ( !q.empty ( ) ){
        int node = q.front ( );
        q.pop ( );
        viz[node] = 0;
        for ( int i = 0; i < graph[node].size ( ); i++ ){
            int new_node = graph[node][i];
            if ( C[node][new_node] - F[node][new_node] > 0 ){
                if ( d[node] + cost[node][new_node] < d[new_node] ){
                    d[new_node] = d[node] + cost[node][new_node];
                    tata[new_node] = node;
                    if ( viz[new_node] == 0 ){
                        q.push ( new_node );
                        viz[new_node] = 1;
                    }
                }
            }
        }
    }
    return d[D] != inf;
}

int main()
{   int m, x, y, c, z, sol = 0, i;
    f >> n;
    for ( i = 1; i <= n; i++ )
        for ( int j = 1; j <= n; j++ ){
            f >> cost[i][n + j];
            graph[i].push_back ( n + j );
            graph[n + j].push_back ( i );
            cost[n + j][i] = -cost[i][n + j];
            C[i][n + j] = 1;
        }
    for ( i = 1; i <= n; i++ ){
        graph[0].push_back ( i );
        C[0][i] = 1;
        graph[n + i].push_back ( 2 * n + 1 );
        C[n + i][2 * n + 1] = 1;
    }
    S = 0, D = 2 * n + 1;
    while ( bfs ( S ) == 1 ){
        int node = D;
        int Min = inf;
        while ( node != S ){
            Min = min ( Min, C[tata[node]][node] - F[tata[node]][node] );
            node = tata[node];
        }
        node = D;
        while ( node != S ){
            F[tata[node]][node] += Min;
            F[node][tata[node]] -= Min;
            node = tata[node];
        }
        sol += d[D] * Min;
    }
    g << sol;
    return 0;
}