Cod sursa(job #2845323)

Utilizator Tudor06MusatTudor Tudor06 Data 7 februarie 2022 18:40:15
Problema Ciclu hamiltonian de cost minim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.23 kb
#include <bits/stdc++.h>

using namespace std;

const int NMAX = 18;
const int INF = 1e9;

long long dp[NMAX + 1][( 1 << NMAX )];
long long cost[NMAX + 1][NMAX + 1];


int main() {
    int n, i, j, m, a, b;
    cin >> n >> m;
    for ( i = 0; i < n; i ++ ) {
        for ( j = 0; j < n; j ++ )
            cost[i][j] = INF;
    }
    for ( i = 0; i < m; i ++ ) {
        cin >> a >> b;
        cin >> cost[a][b];
    }
    for ( i = 0; i < n; i ++ ) {
        for ( j = 0; j < ( 1 << n ); j ++ ) {
            dp[i][j] = INF;
        }
    }
    dp[0][1] = 0;
    for ( j = 0; j < ( 1 << n ) - 1; j ++ ) {
        for ( i = 0; i < n; i ++ ) {
            if ( j & ( 1 << i ) ) {
                for ( int k = 0; k < n; k ++ ) {
                    if ( !(j & ( 1 << k )) ) {
                        dp[k][j | ( 1 << k )] = min( dp[k][j | ( 1 << k )], dp[i][j] + cost[i][k] );
                    }
                }
            }
        }
    }
    long long ans = INF;
    for ( i = 1; i < n; i ++ ) {
        ans = min( ans, dp[i][( 1 << n ) - 1] + cost[i][0] );
    }
//    cout << ans << '\n';
    if ( ans != INF )
        cout << ans << '\n';
    else
        cout << "Nu exista solutie";
    return 0;
}