Pagini recente » Cod sursa (job #1532499) | Cod sursa (job #949093) | Cod sursa (job #2077806) | Cod sursa (job #1306616) | Cod sursa (job #2974686)
#include <bits/stdc++.h>
using namespace std;
const int INF = 18000004;
const int NMAX = 20;
ifstream fin("hamilton.in");
ofstream fout("hamilton.out");
int n, m;
int cost[NMAX][NMAX];
int dp[NMAX][(1 << 18) + 4];
vector<pair<pair<int, int>, int>> edges;
int rez = INF;
int main()
{
fin >> n >> m;
for (int i = 1; i <= m; i++)
{
int a, b, c;
fin >> a >> b >> c;
edges.push_back({{a, b}, c});
cost[a][b] = c;
}
for (int conf = 0; conf < (1 << n); conf++)
{
for (int i = 0; i < n; i++)
{
dp[i][conf] = INF;
}
}
dp[0][1] = 0;
for (int conf = 1; conf < (1 << n); conf++)
{
for (auto edge : edges)
{
int i = edge.first.first;
int j = edge.first.second;
int c = edge.second;
if ((conf & (1 << i)) && (conf & (1 << j)))
{
dp[j][conf] = min(dp[j][conf], dp[i][conf ^ (1 << j)] + c);
}
}
}
for (int i = 1; i < n; i++)
{
if (cost[i][0] != 0)
{
rez = min(rez, dp[i][(1 << n) - 1] + cost[i][0]);
}
}
if (rez == INF)
{
rez = -1;
}
fout << rez;
return 0;
}