Pagini recente » Cod sursa (job #1535928) | Cod sursa (job #174835) | Cod sursa (job #1480340) | Cod sursa (job #1254939) | Cod sursa (job #2833752)
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream cin("hamilton.in");
ofstream cout("hamilton.out");
int n, m, ans = 1e9, dp[262149][20];
struct much {
int y, c;
};
vector<vector<much>> gr;
int main() {
cin >> n >> m;
for (int i = 0; i < n; i++) {
gr.emplace_back(vector<much>());
}
int x, y, ce;
for (int i = 1; i <= m; i++) {
cin >> x >> y >> ce;
gr[x].push_back({ y, ce });
}
int msk = (1 << n) - 1;
for (int i = 0; i < n; i++) {
for (int j = 0; j <= msk; j++) {
dp[j][i] = 1e9;
}
}
dp[0][0] = 0;
queue<pair<int, int>> qu;
qu.push({ 0, 0 });
int act, c, nxt, cost, bit;
while (qu.empty() != 1) {
act = qu.front().first;
c = qu.front().second;
qu.pop();
for (int i = 0; i < gr[act].size(); i++) {
nxt = gr[act][i].y;
cost = gr[act][i].c;
bit = 1 << nxt;
if ((c & bit) == 0) {
if (dp[(c | bit)][nxt] > dp[c][act] + cost) {
dp[(c | bit)][nxt] = dp[c][act] + cost;
qu.push({ nxt , (c | bit) });
}
}
}
}
if (dp[msk][0] == 1e9) {
cout << "Nu exista solutie";
}
else {
cout << dp[msk][0];
}
}