Pagini recente » Cod sursa (job #2813766) | Cod sursa (job #3155943)
#include <fstream>
#include <vector>
using namespace std;
ifstream in ("hamilton.in");
ofstream out ("hamilton.out");
const int max_size = (1 << 18) + 3, INF = 2e9 + 1;
int cost[19][19], dp[max_size][19];
vector <int> mc[19];
int main ()
{
int n, m;
in >> n >> m;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
cost[i][j] = INF;
}
}
for (int i = 0; i < (1 << n); i++)
{
for (int j = 0; j < n; j++)
{
dp[i][j] = INF;
}
}
while (m--)
{
int x, y, c;
in >> x >> y >> c;
cost[x][y] = min(cost[x][y], c);
mc[y].push_back(x);
}
dp[1][0] = 0;
for (int i = 0; i < (1 << n); i++)
{
for (int j = 0; j < n; j++)
{
if ((i & (1 << j)) != 0)
{
for (auto f : mc[j])
{
if ((i & (1 << f)) != 0)
{
dp[i][j] = min(dp[i][j], dp[i ^ (1 << j)][f] + cost[f][j]);
}
}
}
}
}
int ans = INF;
for (auto f : mc[0])
{
ans = min(ans, dp[(1 << n) - 1][f] + cost[f][0]);
}
if (ans == INF)
{
out << "Nu exista solutie";
return 0;
}
out << ans;
in.close();
out.close();
return 0;
}