Cod sursa(job #2171254)

Utilizator chioreanraulChiorean Raul chioreanraul Data 15 martie 2018 11:42:46
Problema Ciclu hamiltonian de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.39 kb
#include <fstream>
#include <vector>

#define INF 1000000000

using namespace std;
int n,m,cost[20][20],dp[(1 << 18)][20],rsp,i,j,k,x,y,c;

vector < int > v[20];
ifstream fin("hamilton.in");
ofstream fout("hamilton.out");

int main()
{
    fin>>n>>m;
    for( i = 0 ; i <= n ; i++ )
        for( j = 0; j <= n; j++ )
            cost[ i ][ j ] = INF;
    for( i = 1; i <= m; i++ )
    {
        fin>>x>>y>>c;
        v[ x ].push_back( y );
        cost[ x ][ y ] = c;
    }
    for( i = 0; i <= ( 1 << n ) - 1; i++ )
    {
        for( j = 0; j <= n; j++ )
            dp[ i ][ j ] = INF;
    }
    dp[ 1 ][ 0 ] = 0 ;
    for( k = 0; k < ( 1 << n ); k++ )
    {
        for( i = 0; i < n; i++ )
        {
            if( ( k & ( 1 << i ) )!= 0 )
            {
                for( auto it : v[ i ] )
                {
                    if( ( k & ( 1 << it ) )== 0 )
                       {
                           dp[ ( k | ( 1 << it ) )][ it ] = min( dp[ ( k | ( 1 << it ) )][ it ], dp[ k ][ i ] + cost[ i ][ it ] );
                       }
                }
            }
        }
    }
    rsp = INF;
    for( i = 0 ; i < n; i++ )
    {
        if( cost[ i ][ 0 ] != INF )
            rsp = min( rsp, dp[ ( 1 << n ) -1 ][ i ] + cost[ i ][ 0 ]);

    }
    if( rsp == INF )
        fout<<"Nu exista solutie";
    else
        fout<<rsp;
    return 0;
}