Question

I have this function and apparently it causes my program to crash:

long long todos(long long x,long long i) {
  x ^= (1 << i);
  long long aux = i - 1;
  if(aux >= 0) x ^= (1 << aux);
  aux = i - 4;
  if(aux >= 0) x ^= (1 << aux);
  aux = i + 1;
  if(aux < 16) x ^= (1 << aux);
  aux = i + 4;
  if(aux < 16) x ^= (1 << aux);
  return x;
}

What I don't understand is why when I change all the ^= ( for &= ~( it runs perfectly fine (although the output I am getting is different). Is there any logical explanation for this behavior?

In case you need the entire code: http://ideone.com/Z7qoof

Was it helpful?

Solution

Looks like your dp() function recurses very deeply. Consider that a call to dp(3) can evaluate all 65536 possible bitboards in sequence with your ^, while with your &~ a call to dp(k) will only evaluate bitboards numerically before k. Notice that you're filling in mat in order in main(); if you only depend on bitboards numerically before k, you won't recurse very deeply.

EDIT: As for fixing this problem, you might think of dynamic programming as being of shortest paths in a directed acyclic graph. The trouble is that you don't have an acyclic graph here. You're doing depth-first search to find shortest paths here, which doesn't...work. Try replacing it with something like breadth-first search or Dijkstra's algorithm.

OTHER TIPS

My guess is that this line crashes:

cout << mat[bs.to_ulong()] << endl;

due to bs being bigger than the reserved space of 1<<16

p.s. why use the long long datatype for everything? long long is 64 bit. Most things you do could probably done with a short int

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top