Cod sursa(job #2949417)

Utilizator Fantastic_Mantudor voicu Fantastic_Man Data 30 noiembrie 2022 16:57:10
Problema Ciclu hamiltonian de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.13 kb
#include <fstream>

using namespace std;
const int nmax = 18;
const int oo = 1e9;

int cost[nmax][nmax];
int dp[( 1 << nmax )][nmax];

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

int main() {
    int n, m, x, y;
    fin >> n >> m;

    for ( int i = 0; i < n; i++ )
        for ( int j = 0; j < n; j++ )
            cost[i][j] = oo;

    for ( int i = 0; i < m; i++ ) {
        fin >> x >> y;
        fin >> cost[x][y];
    }

    for ( int i = 0; i < ( 1 << n ); i++ )
        for ( int j = 0; j < n; j++ )
            dp[i][j] = oo;

    dp[1][0] = 0;
    for ( int i = 1; i < ( 1 << n ); i++ )
        for ( int j = 0; j < n; j++ )
            if ( i & ( 1 << j ) ) {
                for ( int k = 0; k < n; k++ )
                    if ( i & ( 1 << k ) )
                        dp[i][j] = min ( dp[i][j], dp[i ^ ( 1 << j )][k] + cost[k][j] );
            }

    int ans = oo;
    for ( int i = 1; i < n; i++ )
        ans = min ( ans, dp[( 1 << n ) - 1][i] + cost[i][0] );

    if ( ans == oo )
        fout << "Nu exista solutie";
    else
        fout << ans;

    return 0;
}