Nu exista pagina, dar poti sa o creezi ...

Cod sursa(job #2375749)

Utilizator GoogalAbabei Daniel Googal Data 8 martie 2019 11:56:07
Problema Ciclu hamiltonian de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.13 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

ifstream in("hamilton.in");
ofstream out("hamilton.out");

const int NMAX = 20;
const int INF = 1 << 30;
const int MMAX = 263000;

int n, m, res, a[MMAX][NMAX], cost[NMAX][NMAX];
vector < int > v[NMAX];

int main()
{
  int x, y;
  res = INF;
  in >> n >> m;
  for(int i = 0; i < n; i++)
    for(int j = 0; j < n; j++)
      cost[i][j] = INF;

  for(int i = 0; i < (1 << n); i++)
    for(int j = 0; j < n; j++)
      a[i][j] = INF;
  a[1][0] = 0;

  for(int i = 1; i <= m; i++){
    in >> x >> y;
    in >> cost[x][y];
    v[y].push_back(x);
  }

  for(int i = 0; i < (1 << n); i++){
    for(int j = 0; j < n; j++){
      if(i & (1 << j)){
        for(int k = 0; k < v[j].size(); k++){
          if(i & (1 << v[j][k])) {
            a[i][j] = min(a[i][j], a[i ^ (1 << j)][v[j][k]] + cost[v[j][k]][j]);
          }
        }
      }
    }
  }

  for(int i = 0; i < v[0].size(); i++)
    res = min(res, a[(1 << n) - 1][v[0][i]] + cost[v[0][i]][0]);

  if(res == INF)
    out << "Nu exista solutie\n";
  else
    out << res << '\n';

  in.close();
  out.close();

  return 0;
}