Cod sursa(job #1490509)

Utilizator laurageorgescuLaura Georgescu laurageorgescu Data 23 septembrie 2015 18:22:05
Problema Ciclu hamiltonian de cost minim Scor 35
Compilator cpp Status done
Runda Arhiva educationala Marime 1.53 kb
#include<fstream>
#include<vector>

using namespace std;

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

const int nmax = 18;
const int cmax = (1 << nmax);
const int inf = 1 << 30;
int c[ nmax + 1 ][ nmax + 1 ];
int dp[ cmax + 1 ][ nmax + 1 ];

vector< int > g[ nmax + 1 ];

inline int min2( int a, int b ) {
    return ( a < b ? a : b );
}
int main() {
    int n, m;
    fin >> n >> m;

    for( int i = 0; i < n; ++ i ) {
        for( int j = 0; j < n; ++ j ) {
            c[ i ][ j ] = inf;
        }
    }

    for( int i = 0; i < m; ++ i ) {
        int x, y;
        fin >> x >> y;
        g[ y ].push_back( x );
        fin >> c[ x ][ y ];
    }

    for( int i = 0; i < (1 << n); ++ i ) {
        for( int j = 0; j < n; ++ j ) {
            dp[ i ][ j ] = inf;
            if ( i & (1 << j) ) {
                if ( i == (1 << j) ) {
                    dp[ i ][ j ] = 0;
                }
                for( vector< int >::iterator k = g[ j ].begin(); k != g[ j ].end(); ++ k ) {
                    if ( i & (1 << *k) ) {
                        dp[ i ][ j ] = min2( dp[ i ][ j ], dp[ i - (1 << j) ][ *k ] + c[ *k ][ j ] );
                    }
                }
            }
        }
    }

    int ans = inf;
    for( vector< int >::iterator it = g[ 0 ].begin(); it != g[ 0 ].end(); ++ it ) {
        ans = min2( ans, dp[ (1 << n) - 1 ][ *it ] + c[ *it ][ 0 ] );
    }

    if ( ans == inf ) {
        fout << "Nu exista solutie\n";
    } else {
        fout << ans << "\n";
    }
    fin.close();
    fout.close();
    return 0;
}