Pagini recente » Cod sursa (job #1251988) | Borderou de evaluare (job #1504188) | Borderou de evaluare (job #2315359) | Cod sursa (job #2412891) | Cod sursa (job #432113)
Cod sursa(job #432113)
#include <stdio.h>
#include <vector>
#define Nmax 20
#define INF 1000000000
#define Max 262145 // 2^18+1
#define y first
#define c second
#define pb push_back
#define mp make_pair
using namespace std;
vector< pair< int,int > > G[Nmax];
vector< pair< int,int > >:: iterator it;
int cost[Max][Nmax];
int n,m,i,j,costmin;
int x,y,z;
int main(){
freopen("hamilton.in","r",stdin);
freopen("hamilton.out","w",stdout);
scanf("%d%d",&n,&m);
for(i=1;i<=m;++i){
scanf("%d%d%d",&x,&y,&z);
G[y].pb(mp(x,z));
}
for(i=0; i< (1<<n); ++i)
for(j=0; j<n; ++j)
cost[i][j]=INF;
cost[1][0]=0; // ?
for(i=0; i< (1<<n); ++i)
for(j=0; j<n; ++j)
if( i & (1<<j) )
for(it=G[j].begin(); it!=G[j].end(); ++it)
if( i & (1<<(it->y)) )
if( cost[i][j] > cost[i ^ (1<<j)][it->y] + it->c )
cost[i][j] = cost[i ^ (1<<j)][it->y] + it->c;
costmin=INF;
for(it=G[0].begin(); it!=G[0].end(); ++it)
if( cost[(1<<n)-1][it->y] + it->c < costmin )
costmin = cost[(1<<n)-1][it->y] + it->c;
if( costmin == INF ) printf("Nu exista solutie\n");
else printf("%d\n",costmin);
fclose(stdin); fclose(stdout);
return 0;
}