Pagini recente » Cod sursa (job #2788541) | Cod sursa (job #2549111) | Cod sursa (job #226221) | Cod sursa (job #1003773) | Cod sursa (job #2465910)
#include <fstream>
#include <vector>
#include <cstring>
#define inf 0x3f3f3f3f
#define Mmax 263000
using namespace std;
ifstream fin("hamilton.in");
ofstream fout("hamilton.out");
vector <int> A[20];
int Cost[20][20];
int C[Mmax][20];
int rec(int chain, int last)
{
if(C[chain][last] == -1)
{
int i;
C[chain][last] = inf;
for(i = 0; i < A[last].size(); ++i)
if(chain & (1<<A[last][i])){
if(A[last][i] == 0 && ((chain ^ (1<<last)) != (1<<0))) continue;
C[chain][last] = min(C[chain][last], rec(chain ^ (1<<last), A[last][i]) + Cost[A[last][i]][last]);
}
}
return C[chain][last];
}
int main()
{
int i, j, x, y, c, n, m, Sol;
fin >> 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){
fin >> x >> y >> c;
A[y].push_back(x);
Cost[x][y] = c;
}
Sol = inf;
memset(C, -1, sizeof(C));
C[1][0] = 0;
for(j = 0; j < A[0].size(); ++j)
Sol = min(Sol, rec((1<<n)-1, A[0][j]) + Cost[A[0][j]][0]);
if(Sol != inf) fout << Sol;
else fout << "Nu exista solutie";
return 0;
}