Pagini recente » Cod sursa (job #2196028) | Cod sursa (job #2030411) | Cod sursa (job #3039912) | Cod sursa (job #2602123) | Cod sursa (job #3159355)
#include <bits/stdc++.h>
using namespace std;
fstream f("hamiltonian.in", ios::in), g("hamiltonian.out", ios::out);
vector<pair<int, int>> adj[18];
int cost[18][18];
int dp[1 << 18][18];
int main()
{
int n, m;
f >> n >> m;
for (int i = 1; i <= m; i++)
{
int c, x, y;
f >> x >> y >> c;
adj[x].push_back({y, c});
cost[x][y] = c;
}
int mask = (1 << n);
for (int i = 0; i < mask; i++)
for (int j = 0; j < n; j++)
dp[i][j] = 1e9;
dp[1][0] = 0;
for (int i = 0; i < mask; i++)
{
for (int j = 0; j < n; j++)
{
if (i & (1 << j))
{
for (auto x : adj[j])
{
int next = x.first, c = x.second;
if (!(i & (1 << next)))
{
dp[i | (1 << next)][next] = min(dp[i | (1 << next)][next], dp[i][j] + c);
}
}
}
}
}
int ans = 1e9;
for(int i = 0; i < n; i++)
{
if (cost[i][0])
ans = min(ans, dp[mask - 1][i] + cost[i][0]);
}
if (ans == 1e9)
g << "Nu exista solutie";
else
g << ans;
}