Pagini recente » Cod sursa (job #401409) | Cod sursa (job #2871546) | Cod sursa (job #2477454) | Cod sursa (job #2699470) | Cod sursa (job #3274052)
#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;
}