【问题标题】:Shortest hamiltonian path with dynamic programming and bitmasking具有动态规划和位掩码的最短哈密顿路径
【发布时间】:2013-05-14 13:07:08
【问题描述】:

我刚刚在http://codeforces.com/blog/entry/337 处阅读了一篇关于如何使用动态编程找到最短哈密顿路径的文章。

虽然伪代码有效,但我不明白为什么我必须在集合上使用 xor 运算符和 2^i。

您为什么不直接从位掩码中减去当前访问过的城市?为了让算法发挥作用,集合的异或有什么魔力?

这里要澄清的是一段用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];
        }

        for (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];
    }

【问题讨论】:

  • 你试过改写成dp[set][i] = Math.min(dp[set][i], calculate(set - 1&lt;&lt;i, city) + dist[i][city]);吗?我认为它也应该可以正常工作。

标签: dynamic-programming xor bitmask


【解决方案1】:

找到了我的问题的解决方案,^ 是一个位翻转。因此,如果您有一个位掩码并在掩码上使用 xor 运算符,您将翻转该位置的位。例如。 1010 ^ (1

减法也有效,但使用 xor 运算符,您可以确定您只触摸该位置的位,而不会触摸其他位置。图像 1000 - (1

【讨论】:

  • 我明白了。我觉得没关系。两者都是安全的。异或也改变进位位。我认为它也很容易仅适用于二进制逻辑。
猜你喜欢
  • 1970-01-01
  • 2020-10-03
  • 2012-10-26
  • 1970-01-01
  • 1970-01-01
  • 2023-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多