xor - Shortest hamiltonian path with dynamic programming and bitmasking -


i've read article how find shortest hamiltonian path using dynamic programming here http://codeforces.com/blog/entry/337.

while pseudocode works, not understand why have take use xor operator on set , 2^i.

why wouldn't substract current visisted city bitmask? xor set in order make algorithm it's magic?

to clarify here piece of pseudocode written in java:

public int calculate(int set, int i){          if(count(set) == 1 && (set & 1<<i) != 0){             return 0;         }          if ( dp[set][i] != infinity){             return dp[set][i];         }          (int city=0;city<n;city++){             if((set & 1<<city) == 0) continue;             dp[set][i] = math.min(dp[set][i], calculate(set ^ 1<<i, city) + dist[i][city]);         }         return dp[set][i];     } 

found solution problem, ^ bitflip. if have bitmask , use xor operator on mask, flip bit on place. e.g. 1010 ^ (1<<1) results in 1000. same goes 1000 ^ (1<<1) = 1010.

the substraction works, xor operator know touch bit @ place, , none else. image 1000 - (1<1), result in entirely different. substraction works , can used if 100% sure @ 1 @ place i, xor safer.


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -