fork download
  1. #include <iostream>
  2. #include <fstream>
  3. #define FIN "hamilton.in"
  4. #define FOUT "hamilton.out"
  5.  
  6. using namespace std;
  7.  
  8. const int INF = 100000000;
  9. const int MAXN = 20;
  10.  
  11. int n, m, sol;
  12. int Cost[ MAXN ][ MAXN ],
  13. P[ MAXN ],
  14. Used[ MAXN ];
  15.  
  16. void back(int level) {
  17.  
  18. if(level > n) {
  19.  
  20. int summa = Cost[P[n]][P[1]];
  21.  
  22. for(int i = 1; i < n; ++i) {
  23.  
  24. summa += Cost[ P[i] ][ P[i+1] ];
  25. }
  26.  
  27. sol = min(sol, summa);
  28.  
  29. return;
  30.  
  31. }
  32.  
  33. for(int i = 0; i < n; ++i) {
  34.  
  35. if( !Used[i] ) {
  36. P[ level ] = i;
  37. Used[i] = 1;
  38. back(level + 1);
  39. Used[i] = 0;
  40. }
  41. }
  42.  
  43. }
  44.  
  45. int main(int argc, char const *argv[]) {
  46.  
  47. int x,
  48. y;
  49.  
  50. ifstream fin(FIN);
  51.  
  52. ofstream fout(FOUT);
  53.  
  54. cin>>n>>m;
  55.  
  56. sol = INF;
  57. for(int i = 0; i < n; i++)
  58. for(int j = 0; j < n; ++j)
  59. Cost[i][j] = INF;
  60.  
  61. while( m-- ){
  62. cin>>x>>y;
  63. cin>>Cost[x][y];
  64. }
  65.  
  66. back(1);
  67.  
  68. if(sol == INF) {
  69. cout<<"Nu exista solutie";
  70. } else {
  71. cout<<sol;
  72. }
  73.  
  74. return 0;
  75. }
Success #stdin #stdout 0.01s 5640KB
stdin
5 10
0 1 9
0 3 8
1 0 7
1 2 1
1 4 3
2 0 5
2 4 4
3 2 6
4 3 7
4 1 1
stdout
26