Pagini recente » Cod sursa (job #578699) | Cod sursa (job #33759) | Cod sursa (job #1597256) | Cod sursa (job #1185901) | Cod sursa (job #2665709)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("hamilton.in");
ofstream fout("hamilton.out");
int dp[20][500000], cost[20][20];
int n,m;
void build()
{
int total = (1 << n);
for(int i = 1; i <= n; ++i)
for(int mask = 0; mask < total; ++mask)
dp[i][mask] = 1 << 29;
for(int i = 2; i <= n; ++i)
dp[i][ 1 << i - 1] = cost[1][i];
for (int mask = 0; mask < total; ++mask) {
for (int i = 1; i <= n; ++i) {
if (!(mask & (1 << i - 1))) continue;
if (dp[i][mask] == (1 << 29)) continue;
for (int j = 1; j <= n; ++j) {
if (mask & (1 << j - 1)) continue;
int newm = mask | (1 << j - 1);
dp[j][newm] = min (dp[j][newm], dp[i][mask] + cost[i][j]);
}
}
}
}
int main() {
fin >> n >> m;
for(int i = 1; i <= n; ++i)
for(int j = 1; j <= n; ++j)
cost[i][j] = 1 << 29;
for(int i = 1; i <= m; ++i)
{
int x, y, c;
fin >> x >> y >> c;
x += 1;
y += 1;
cost[x][y] = min(cost[x][y], c);
}
build();
if (dp[1][(1 << n) - 1] < (1 << 29))
fout << dp[1][(1 << n) - 1];
else
fout << "Nu exista solutie";
return 0;
}