Pagini recente » Cod sursa (job #313402) | Cod sursa (job #2143962) | Cod sursa (job #25001) | Cod sursa (job #279160) | Cod sursa (job #2653030)
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
vector<pair<int,int>> *g;
vector<int> h;
vector<bool> viz;
int n, min_cost = 1e9;
void show() {
for (auto u : h)
cout << u << ' ';
cout << '\n';
}
void bt(int u,int cost) {
viz[u] = true;
h.push_back(u);
if (h.size() == n) {
for (auto v : g[u])
if (v.first == h[0]) {
if (cost + v.second < min_cost)
min_cost = cost + v.second;
break;
}
}
else {
for (auto v : g[u])
if (!viz[v.first])
bt(v.first, cost + v.second);
}
h.pop_back();
viz[u] = false;
}
int main() {
ifstream fin("hamilton.in");
ofstream fout("hamilton.out");
int m;
fin >> n >> m;
g = new vector<pair<int,int>>[n + 1];
viz.resize(n + 1, false);
while (m--) {
int x, y, z;
fin >> x >> y >> z;
g[x].push_back({ y,z });
}
bt(0, 0);
if (min_cost != 1e9)
fout << min_cost;
else fout << "Nu exista solutie";
delete[] g;
return 0;
}