3-PARTITION problem

后端 未结 6 2016
醉酒成梦
醉酒成梦 2020-12-05 05:56

here is another dynamic programming question (Vazirani ch6)

Consider the following 3-PARTITION problem. Given integers a1...an, we want to determine whet

6条回答
  •  悲哀的现实
    2020-12-05 06:34

    As I have answered in same another question like this, the C++ implementation would look something like this:

    int partition3(vector &A)
    {
      int sum = accumulate(A.begin(), A.end(), 0);
      if (sum % 3 != 0)
      {
        return false;
      }
      int size = A.size();
    
      vector> dp(sum + 1, vector(sum + 1, 0));
      dp[0][0] = true;
    
      // process the numbers one by one
      for (int i = 0; i < size; i++)
      {
        for (int j = sum; j >= 0; --j)
        {
          for (int k = sum; k >= 0; --k)
          {
            if (dp[j][k])
            {
              dp[j + A[i]][k] = true;
              dp[j][k + A[i]] = true;
            }
          }
        }
      }
      return dp[sum / 3][sum / 3];
    }
    

提交回复
热议问题