一道dp题,常用算法是多重背包
降低时间复杂度的主要方法有:
1.利用二进制优化转换为01背包问题
2.POJ的discussion中提出的取模优化方法
这两种算法网上有很详细的总结,不多说
现在我要讨论的是,这题真的是一道背包问题吗?
我们都知道,背包问题中每个物品是有两个属性的,重量和价值,但是本题中的物品有且只有一个属性,
如果我们强行使重量和价值相等为物品赋予第二个属性,其实是一种浪费,
处理更多的属性很可能带来更高的时间复杂度。
那这题更贴近哪种问题呢?
依旧是POJ的discussion中给出的思路,这题本质上是一道部分和问题。
我们关注的只是某个值是否存在,而不关注在这个值存在的前提下,能否得到最大价值。
#include <iostream>
#include <cstring>
using namespace std;
int dp[120000];
int a[] = { 1,2,3,4,5,6 };
int m[6];
int main()
{
int kase = 1;
while (1)
{
int s = 0;
for (int i = 0; i < 6; i++) {
cin >> m[i];
s += m[i]*a[i];
}
if (s == 0)
break;
if (s % 2 == 1) {
printf("Collection #%d:\nCan't be divided.\n\n",kase++);
continue;
}
memset(dp, -1, sizeof(dp));
dp[0] = 0;
s = s / 2;
for (int i = 0; i < 6; i++)
for (int j = 0; j <= s; j++)
if (dp[j] >= 0)
dp[j] = m[i];
else if (j < a[i] || dp[j - a[i]] <= 0)
dp[j] = -1;
else
dp[j] = dp[j - a[i]] - 1;
if(dp[s]>=0)
printf("Collection #%d:\nCan be divided.\n\n", kase++);
else
printf("Collection #%d:\nCan't be divided.\n\n", kase++);
}
return 0;
}