方阵上的最大和

时间:2014-05-18 15:48:46

标签: algorithm matrix

  

给定n×n大小的方阵,其中每个单元由...表示   一个正整数,从该矩阵中找到n个整数的列表   它们的总和尽可能大,但没有两个整数   出现在初始矩阵的同一行或列中。

所以我最好的想法是,因为我们知道选择要添加到总和中的单元格意味着同一行和列中的所有单元格将无法再到达那里,我们可以计算出“成本”给定的细胞有。由于行的总和对于行中的每个单元格是相同的,我们可能会忽略它们的计算。更正式地说:

for each cell in each row:
    if (columnNotYetVisited AND (-1 * sumOfTheColumn) + (2 * valueOfTheCell) > currentMax):
        currentMax = (-1 * sumOfTheColumn) + (2 * valueOfTheCell);

if endOftheRow:
    mark columnWithBestCost as visited;
    add currentMax to finalSum;

虽然它确实适用于某些输入,但有一些输入失败了很多。那么这个问题的最佳方法是什么呢?

编辑:另外,我现在对我进行了一次样本测试,以防它派上用场:

7   53  183 439
627 343 773 959
447 283 463 29
217 623 3   399

被修改     OUT:2282(439 + 773 + 447 + 623)

1 个答案:

答案 0 :(得分:2)

我使用动态编程位掩码

解决了问题
//                 bitmask      
int F(int stage, int selecion)
{
  if(stage == N) return selecion == (1<<N)-1 ? 0 : -INF;

  if(dp[stage][selecion] != -1)
    return dp[stage][selecion];

  int answer = -INF;

  for(int i = 0;i < N;i++)
    if((selecion & (1 << i)) == 0) 
        answer = max(answer, matrix[i][stage] + F(stage+1, selecion | (1 << i) ) );

  dp[stage][selecion] = answer;

  return answer;
}

here我的所有代码

我认为它可以用其他算法解决为hungarian,但它适用于小矩阵(20x20)

如果你对编程竞赛感兴趣,你可能想尝试this spoj problem(它有一个特技案例,因为你不能选择零0)

相关问题