Cod sursa(job #822973)

Utilizator MtkMarianHagrSnaf MtkMarian Data 24 noiembrie 2012 13:03:41
Problema Ciclu hamiltonian de cost minim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.46 kb
#include<cstdio>
#include<vector>
#include<string.h>

using namespace std;

#define INF 100000000
#define NMAX 20
#define MAX 262150

int n,m,cst,x,y ;
int cost[NMAX][NMAX],vizcost[MAX][NMAX],REZ;


vector< int > g[NMAX];

inline int min (int a , int b )
{
	return a < b ? a : b ;
}

int hamilt( int a , int conf , int b )
{
	if( vizcost[ conf ][ b ] == -1 )
	{
	
			vizcost[conf][ b ] = INF ;
			for(int i = 0 ; i < g[b].size() ; ++i  )
				if(conf&( 1<<g[b][i] ))
				{
					if( g[b][i] == a && (conf^( 1<<b )) != (1<<a)  ) continue ;

					vizcost[conf][b] = min ( vizcost[conf][b] , ( hamilt (a , conf^(1<<b) , g[b][i] ) + cost[g[ b ][ i ]][ b ])	);

				}	
	}

		
	return vizcost[conf][b];

}

void hamilton_r()
{
	for(int i = 0 ; i < n ; ++i )
	{
		
		memset(vizcost , -1 , sizeof( vizcost ) ) ;
		vizcost[ 1<<i ][ i ]= 0;

		for( int j = 0 ; j<g[i].size(); ++j )
				REZ = min ( REZ , (hamilt(i , (1<<n)-1 , g[i][j]) + cost[g[ i ][ j ]][ i ] ));

	}
}

void citeste()
{
	scanf("%d %d",&n,&m);

	for(int i = 0 ;i<n ; ++i  )
		for(int j = 0 ; j < n ; ++j) cost[i][j] = INF;
	
	for(int i=1 ; i<= m; ++i)
	{
		scanf("%d %d %d",&x,&y,&cst);
		g[y].push_back(x);
		cost[x][y]= cst ;
	}
	REZ= INF ;

}

int main()
{
	freopen("hamilton.in","r",stdin);
	freopen("hamilton.out","w",stdout);
	
	citeste();
	
	hamilton_r();
	
	if(REZ != INF)	printf("%d\n",REZ);
	else 	printf("Nu exista solutie\n");
	
	return 0;
	
}