Cod sursa(job #2833752)

Utilizator Langa_bLanga Radu Langa_b Data 15 ianuarie 2022 16:55:27
Problema Ciclu hamiltonian de cost minim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.13 kb
#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];
	}
}