Cod sursa(job #1534042)

Utilizator papinubPapa Victor papinub Data 23 noiembrie 2015 11:01:05
Problema Ciclu hamiltonian de cost minim Scor 35
Compilator cpp Status done
Runda Arhiva educationala Marime 1.42 kb
#include <cstdio>

using namespace std;

const int MAX_N = 18;
const int MAX_INF = 0x7fffffff;
                 // 0111 1111 1111 1111 1111 1111 1111 1111 == (2^31)-1
const int MIN_INF = 0x80000000;
                 // 1000 0000 0000 0000 0000 0000 0000 0000 == -(2^31)

                 // 1111 1111 1111 1111 1111 1111 1111 1111 == -1
                 // 0000 0000 0000 0000 0000 0000 0000 0001 ==  1

int cost[1 + MAX_N][1 + MAX_N];
int drum[1 + MAX_N];
int n, m;

bool folosit[1 + MAX_N];
int costSol;

int minim;

void back(int k) { // k = nr. de noduri din ciclu
  int u = drum[k - 1]; // u = ultimul nod
  if (k == n+1 && u == 1)
  {
    if (costSol < minim)
    {
      minim = costSol;
    }
  }
  else
  {
    for (int v = 0; v < n; v++)
    {
	   if (!folosit[v] && cost[u][v] > 0)
      {
        costSol += cost[u][v]; // costul de la nodul u la nodul v;
        folosit[v] = true;
        drum[k] = v;
	     back(k+1);
        folosit[v]= false;
        costSol -= cost[u][v];
      }
    }
  }
}

int main() {
  int i;
  freopen("hamilton.in", "r", stdin);
  freopen("hamilton.out", "w", stdout);
  scanf("%d%d", &n, &m);
  for (i = 0; i < m; i++) {
    int u, v, c;
    scanf("%d%d%d", &u, &v, &c);
    cost[u][v] = c;
  }
  minim = MAX_INF;
  drum[0] = 1;
  back(1);

  if (minim == MAX_INF)
    printf("Nu exista solutie");
  else
    printf("%d\n", minim);
  return 0;
}