Cod sursa(job #2861397)

Utilizator DooMeDCristian Alexutan DooMeD Data 3 martie 2022 21:44:01
Problema Ciclu hamiltonian de cost minim Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.75 kb
#include <bits/stdc++.h>
using namespace std;
const int nmax = 18;
const int inf = 0x3f3f3f3f;

vector<vector<pair<int,int>>> dx(nmax);
int dp[(1<<nmax)][nmax];

int main() {
	ifstream f("hamilton.in");
	ofstream g("hamilton.out");
	
	int n,m; f >> n >> m;
	for(int i=1; i<=m; i++) {
		int x,y,c; f >> x >> y >> c;
		dx[y].emplace_back(x,c);
	}
	
	
	for(int i=0; i<(1<<n); i++)
		for(int j=0; j<n; j++)
			dp[i][j] = inf;
	
	dp[0][1] = 0;
	for(int i=0; i<(1<<n); i++) 
		for(int j=0; j<n; j++) 
			if( (i&(1<<j)) ) 
				for(auto x : dx[j]) 
					dp[i][j] = min(dp[i][j], dp[i^(1<<j)][x.first] + x.second);
					
			
	int mn = inf;				
	for(auto i : dx[0])
		mn = min(mn, dp[(1<<n)-1][i.first] + i.second);
	if(mn!=inf) g << mn;
	else g << "Nu exista solutie";
	return 0;
}