Pagini recente » Cod sursa (job #3163297) | Cod sursa (job #1413622) | Cod sursa (job #1892063) | Cod sursa (job #2776581) | Cod sursa (job #775949)
Cod sursa(job #775949)
#include<cstdio>
#include<list>
#define filein "hamilton.in"
#define fileout "hamilton.out"
using namespace std;
const int inf = 100000000;
int N,M;
int i,j,minim,v,sol;
int cost[20][20];
int mat[300000][20];
list<int> L[20];
list<int>::iterator it;
int main()
{int a,b,c;
freopen(filein,"r",stdin);
freopen(fileout,"w",stdout);
scanf("%d %d",&N,&M);
for(i=0; i<N; i++)
for(j=0; j<N; j++)
cost[i][j]=inf;
for(i=1; i<=M; i++)
{scanf("%d %d %d",&a,&b,&c);
cost[a][b]=c;
L[b].push_back(a);}
for(i=0; i<(1<<N); i++)
for(j=0; j<N; j++)
mat[i][j]=inf;
mat[1][0]=0;
for(i=1; i<(1<<N); i++)
for(j=0; j<N; j++)
if(i&(1<<j))
{for(it=L[j].begin(); it!=L[j].end(); it++)
if(i&(1<<(*it)))
if(mat[i][j]>mat[i^(1<<j)][*it]+cost[*it][j])
mat[i][j]=mat[i^(1<<j)][*it]+cost[*it][j];
}
sol=inf;
for(it=L[0].begin(); it!=L[0].end(); it++)
if(sol>mat[(1<<N)-1][*it]+cost[*it][0])
sol=mat[(1<<N)-1][*it]+cost[*it][0];
if(sol!=inf)
printf("%d",sol);
else
printf("Nu exista solutie");
return 0;}