Cod sursa(job #2693938)

Utilizator TheGodFather2131Alexandru Miclea TheGodFather2131 Data 7 ianuarie 2021 17:02:49
Problema Ciclu hamiltonian de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.77 kb
//ALEXANDRU MICLEA

#include <vector>
#include <algorithm>
#include <string>
#include <string.h>
#include <cstring>
#include <queue>
#include <map>
#include <set>
#include <unordered_map>
#include <time.h>
#include <iomanip>
#include <deque>
#include <math.h>
#include <cmath>
#include <assert.h>
#include <stack>
#include <bitset>
#include <random>
#include <chrono>
#include <assert.h>
#include <iostream>

using namespace std;
using ll = long long;

#define fast_cin() 	ios::sync_with_stdio(false); cin.tie(0); cout.tie(0)

//VARIABLES

const int maxn = (1 << 18);

int dp[maxn + 10][20];
int gr[20][20];
vector <int> masks[20];
int inf = 1e9 + 5;

//FUNCTIONS



//MAIN

int main() {

	#ifdef INFOARENA
	freopen("hamilton.in", "r", stdin);
	freopen("hamilton.out", "w", stdout);
	#endif

	fast_cin();

	int n, m; cin >> n >> m;
	for (int i = 1; i <= m; i++) {
		int a, b, val; cin >> a >> b >> val;
		gr[a][b] = val;
	}

	for (int mask = 0; mask < (1 << n); mask++) {
		int cont = 0;
		for (int i = 0; i < n; i++) {
			if (mask & (1 << i)) cont++;
		}
		masks[cont].push_back(mask);
	}

	for (int i = 1; i <= n; i++) 
		for (auto& x : masks[i]) 
			for (int l = 0; l < n; l++)
				if (dp[x][l] || (x == 1) && (l == 0))
					for (int bit = 0; bit < n; bit++)
						if (!(x & (1 << bit)) && gr[l][bit])
							if (dp[x + (1 << bit)][bit] == 0)
								dp[x + (1 << bit)][bit] = dp[x][l] + gr[l][bit];
							else
								dp[x + (1 << bit)][bit] = min(dp[x + (1 << bit)][bit], dp[x][l] + gr[l][bit]);


	int ans = inf;

	for (int i = 0; i < n; i++) {
		if (dp[(1 << n) - 1][i] && gr[i][0])
			ans = min(ans, dp[(1 << n) - 1][i] + gr[i][0]);
	}

	if (ans == inf) cout << "Nu exista solutie";
	else cout << ans;

	return 0;
}