Cod sursa(job #3215590)

Utilizator PostoacaMateiMatei Postoaca PostoacaMatei Data 15 martie 2024 10:25:21
Problema Ciclu hamiltonian de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.9 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin("hamilton.in");
ofstream fout("hamilton.out");

typedef long long ll;
typedef pair<int, int> ii;
typedef vector<int> vi;
typedef vector<ii> vii;
const int inf = 1e9;
const int mod = 1e9 + 7;

int n, m;
vi adj[21];
int cost[21][21];
int dp[1 << 19][21];

int main() {
	fin >> n >> m;
	for (int i = 1; i <= m; i++) {
		int x, y;
		fin >> x >> y;
		adj[y].push_back(x);
		fin >> cost[x][y];
	}
	for (int i = 0; i < (1 << n); i++)
		for (int j = 0; j < n; j++)
			dp[i][j] = inf;
	dp[1][0] = 0;
	for (int i = 0; i < (1 << n); i++)
		for (int j = 0; j < n; j++)
			if (i & (1 << j))
				for (int k : adj[j])
					if (i & (1 << k))
						dp[i][j] = min(dp[i][j], dp[i ^ (1 << j)][k] + cost[k][j]);
	int ans = inf;
	for (int i : adj[0])
		ans = min(ans, dp[(1 << n) - 1][i] + cost[i][0]);
	if (ans != inf)
		fout << ans;
	else
		fout << "Nu exista solutie";
	return 0;
}