Pagini recente » Cod sursa (job #830768) | Cod sursa (job #3273476) | Cod sursa (job #486159) | Cod sursa (job #1796377) | Cod sursa (job #3150906)
#include <iostream>
#include <fstream>
#include <vector>
#include <cstring>
#include <queue>
using namespace std;
#define oo 0x3f3f3f3f
ifstream f("hamilton.in");
ofstream g("hamilton.out");
int n, m;
int dp[(1 << 18)][18], cost[18][18];
vector<int> graph[18];
void read() {
f>>n>>m;
int x, y;
for(int i = 1;i <= m;++i) {
f>>x>>y>>cost[y][x];
graph[y].push_back(x);
}
}
int dfs(int conf, int node) {
if(dp[conf][node] == -1) {
dp[conf][node] = oo;
for(const auto& ngh : graph[node]) {
if((1 << ngh) & conf) {
if(ngh == 0 && 1 + (1 << node) != conf) {
continue;
}
dp[conf][node] = min(dp[conf][node], dfs(conf ^ (1 << node), ngh) + cost[node][ngh]);
}
}
}
return dp[conf][node];
}
void solve() {
memset(dp, -1, sizeof(dp));
dp[1][0] = 0;
int result = oo;
for(const auto& node : graph[0]) {
result = min(result, dfs((1 << n) - 1, node) + cost[0][node]);
}
if(result < oo) {
g<<result;
return;
}
g<<"Nu exista solutie";
}
int main() {
read();
solve();
return 0;
}