Cod sursa(job #823026)

Utilizator MtkMarianHagrSnaf MtkMarian Data 24 noiembrie 2012 14:45:22
Problema Ciclu hamiltonian de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.32 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 ;
}

void hamilton_r()
{

	
	for(int i=0  ; i<(1<<n) ; ++i)		
		for( int j = 0 ; j < n ; ++j )	
			vizcost[i][j]=INF;
		
	vizcost[1][0]=0;

	
		for(int i=0  ; i<(1<<n) ; ++i)		
			for( int j = 0 ; j < n ; ++j )				
				if( i&(1<<j) )				
					for(int k = 0 ; k < g[j].size() ; ++k  )				
						if( i&(1<<g[j][k]) )			
							vizcost[i][j] = min ( vizcost[i][j], vizcost[(i^(1<<j))][g[j][k]]  + cost[g[ j ][ k ]][ j ])	;
						
						
		for(int i=0 ;i< g[0].size();++i)				
					REZ = min ( REZ ,  vizcost[(1<<n)-1][g[0][i]] +cost[g[0][i]][0] );

	
}

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;
	
}