华为oj上的购物单问题,背包问题的变种,动态规划

原题可以看华为oj上的购物单问题。

牛客上也有


#define max(x,y) (x)>(y)?(x):(y)


using namespace std;


int main()
{
int N, m;   //N 总钱数  m为购买物品个数
int weight[61][3] = { 0 };
int value[61][3] = { 0 };


while (cin >> N >> m)
{
int dp[61][3201] = { 0 };
N /= 10;    //都是10的整数倍 节约空间
int v, p, q;
for (int i = 1; i <= m; i++)
{
cin >> v >> p >> q;
p = p*v;
v /= 10;
//按主件附件分类  第二个小标表示是第i件物品还是主件附件
if (q == 0)
{
weight[i][q] = v;
value[i][q] = p;
}
else if (weight[q][1] == 0)
{
weight[q][1] = v;
value[q][1] = p;
}
else
{
weight[q][2] = v;
value[q][2] = p;
}


}


//开始进行动态规划
for (int i = 1; i <= m; i++)
for (int j = 1; j <= N; j++)
{
dp[i][j] = dp[i - 1][j];
if (weight[i][0] <= j)
{
int t = max(dp[i - 1][j], dp[i - 1][j - weight[i][0]] + value[i][0]);
if (t>dp[i][j])
dp[i][j] = t;
}
if (weight[i][0] + weight[i][1] <= j)
{
int t = dp[i - 1][j - weight[i][0] - weight[i][1]] + value[i][0] + value[i][1];
if (t>dp[i][j])
dp[i][j] = t;
}
if (weight[i][0] + weight[i][2] <= j)
{
int t = dp[i - 1][j - weight[i][0] - weight[i][2]] + value[i][0] + value[i][2];
if (t>dp[i][j])
dp[i][j] = t;
}
if (weight[i][0] + weight[i][1] + weight[i][2] <= j)
{
int t = dp[i - 1][j - weight[i][0] - weight[i][1] - weight[i][2]] + value[i][0] + value[i][1] + value[i][2];
if (t>dp[i][j])
dp[i][j] = t;
}
}


cout << dp[m][N] << endl;


}
return 0;
}

你可能感兴趣的:(针对IT笔试的几种常用算法)