Pagini recente » Cod sursa (job #2406044) | Cod sursa (job #1756876) | Cod sursa (job #1665633) | Cod sursa (job #71650) | Cod sursa (job #2843530)
#include <iostream>
#include <vector>
#include <fstream>
#define MAXMASK 262152
#define MAXN 20
#define INF (1<<29)
using namespace std;
int n,m,x,y,cost,f[MAXN];
int dp[MAXMASK][MAXN];
vector<pair<int, int>> L[MAXN];
ifstream fin("hamilton.in");
ofstream fout("hamilton.out");
int main()
{
fin >> n >> m;
/// intializam toate valorile dp cu INF
for(int codStare = 1; codStare < (1<<n); codStare += 2){
for(int last = 0; last < n; last++){
dp[codStare][last] = INF;
}
}
/// citim, realizam lista de vecini
for(int i = 1; i <= m; i++){
fin >> x >> y >> cost;
L[x].push_back({y, cost});
if(y == 0){
f[x] = cost;
}
}
dp[1][0] = 0;
for(int codStare = 1; codStare < (1<<n); codStare += 2){
for(int last = 0; last < n; last++){
if(dp[codStare][last] != INF){
for(int i = 0; i < L[last].size(); i++){
int x = L[last][i].first;
int cost = L[last][i].second;
if( ( (codStare >> last) & 1 ) == 1 ){
if(( (codStare >> x) & 1 ) == 0)
dp[codStare+(1<<x)][x] = min(dp[codStare+(1<<x)][x], dp[codStare][last]+cost);
}
}
}
}
}
int sol = INF;
for(int last = 1; last < n; last++){
if(f[last] != 0 && dp[(1<<n)-1][last] != INF){
sol = min(sol, dp[(1<<n)-1][last]+f[last]);
}
}
if(sol != INF){
fout << sol << "\n";
}else{
fout << "Nu exista solutie\n";
}
return 0;
}