Cod sursa(job #3274052)

Utilizator CosminaneBoac Mihai Cosmin Cosminane Data 4 februarie 2025 21:29:42
Problema Ciclu hamiltonian de cost minim Scor 25
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.04 kb
#include <fstream>
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
struct muchie{
	int y, c;
};
bool comp(muchie a, muchie b){
	return a.c < b.c;
}
int f[20], trecut, cost, n;
vector <muchie> v[20];
static bool solve(int x){
	int i;
	//cout << x << ' ' << trecut << ' ' << cost << '\n';
	if( x == 0 && trecut == n + 1 ){
		return true;
	}
	for( i = 0; i < v[x].size(); i++ ){
		if( f[v[x][i].y] == 0 ){
			cost += v[x][i].c;
			f[v[x][i].y] = 1;
			trecut++;
			if( solve(v[x][i].y) ){
				return true;
			}
			trecut--;
			f[v[x][i].y] = 0;
			cost -= v[x][i].c;
		}
	}
	return false;
}
int main(){
	int m, i, x, y, c;
	ifstream fin( "hamilton.in" );
	ofstream fout( "hamilton.out" );
	fin >> n >> m;
	for( i = 0; i < m; i++ ){
		fin >> x >> y >> c;
		v[x].push_back( { y, c } );
	}
	for( i = 0; i < n; i++ ){
		sort( v[i].begin(), v[i].end(), comp );
	}
	trecut = 1;
	cost = 0;
	if( solve( 0 ) == false ){
		fout << "Nu exista solutie";
	}
	else{
		fout << cost;
	}
	return 0;
}