Cod sursa(job #532268)

Utilizator andreitheo87Teodorescu Andrei-Marius andreitheo87 Data 11 februarie 2011 11:33:28
Problema Ciclu hamiltonian de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.12 kb
#include <stdio.h>
#include <string.h>

struct Node {
  Node(int vec_, int cost_) {
    vec=vec_;
    cost = cost_;
  }
  int vec, cost;
  Node* next;
};
int mat[18][1<<18];

int main() {
  freopen("hamilton.in", "r", stdin);
  freopen("hamilton.out", "w", stdout);
  int n, m;
  scanf("%d %d", &n, &m);
  Node* vecs[20];
  memset(vecs, 0, sizeof(vecs));
  for (int i=0; i<m; i++) {
    int x, y, cost;
    scanf("%d %d %d", &x, &y, &cost);
    Node* newNode = new Node(y, cost);
    newNode->next = vecs[x];
    vecs[x] = newNode;
  }
  memset(mat, -1, sizeof(mat));
  mat[0][0] = 0;
  for (int conf=0; conf<1<<n; conf++) {
    for (int last=0; last<n; last++) {
      if (mat[last][conf] != -1) {
	Node* it = vecs[last];
	while (it) {
	  if ((conf&(1<<it->vec)) == 0) {
	    int newConf = conf + (1<<it->vec);
	    if (mat[it->vec][newConf] == -1 ||
		mat[it->vec][newConf] > mat[last][conf] + it->cost) {
	      mat[it->vec][newConf] = mat[last][conf] + it->cost;
	    }
	  }
	  it = it->next;
	}
      }
    }
  }
  if (mat[0][(1<<n)-1] == -1) {
    printf("Nu exista solutie\n");
  } else printf("%d\n", mat[0][(1<<n)-1]);
  return 0;
}