Pagini recente » Cod sursa (job #134086) | Cod sursa (job #523958) | Cod sursa (job #2196536) | Cod sursa (job #2959685) | Cod sursa (job #815520)
Cod sursa(job #815520)
#include <cstdio>
#include <algorithm>
using namespace std;
inline int next_int() {
int d;
scanf("%d", &d);
return d;
}
const int V = 18;
const int E = V * V;
const int INF = 1e9;
int n, m;
int cost[V][V];
bool seen[V][1 << V];
int dp[V][1 << V];
int LG[1 << V];
int f(const int & u, const int & mask) {
if (mask == 0) {
return cost[u][0];
}
if (seen[u][mask]) {
return dp[u][mask];
}
seen[u][mask] = true;
dp[u][mask] = INF;
int copy = mask;
while (copy) {
int v = LG[copy & -copy];
copy -= copy & -copy;
if ((mask & (1 << v))) {
dp[u][mask] = min(dp[u][mask], cost[u][v] + f(v, mask ^ (1 << v)));
}
}
return dp[u][mask];
}
int main() {
for (int i = 0; i < V; i++) {
LG[1 << i] = i;
}
freopen("hamilton.in", "r", stdin);
freopen("hamilton.out", "w", stdout);
n = next_int();
m = next_int();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cost[i][j] = INF;
}
}
for (int i = 0; i < m; i++) {
int u = next_int();
int v = next_int();
int w = next_int();
cost[u][v] = w;
}
int ans = f(0, (1 << n) - 2);
if (ans < INF) {
printf("%d", ans);
} else {
printf("Nu exista solutie");
}
return 0;
}