dp--Bone Collector

来源:互联网 发布:网络黑侠哪本作品好 编辑:程序博客网 时间:2024/06/04 08:49
Many years ago , in Teddy’s hometown there was a man who wascalled “Bone Collector”. This man like to collect varies of bones ,such as dog’s , cow’s , also he went to the grave …
The bone collector had a big bag with a volume of V ,and along histrip of collecting there are a lot of bones , obviously , differentbone has different value and different volume, now given the eachbone’s value along his trip , can you calculate out the maximum ofthe total value the bone collector can get ?

dp--Bone <wbr>Collector

Input
The first line contain a integer T , the number ofcases.
Followed by T cases , each case three lines , the first linecontain two integer N , V, (N <= 1000 , V <= 1000)representing the number of bones and the volume of his bag. Andthe second line contain N integers representing the value of eachbone. The third line contain N integers representing the volume ofeach bone.
Output
One integer per line representing the maximum of the totalvalue (this number will be less than 2 31).
Sample Input
15 101 2 3 4 55 4 3 2 1
Sample Output
14
最典型的01背包,本质其实也是和爬楼梯一样,将volume分解成子问题研究(爬楼梯中是将阶数分解),只不过爬楼梯不是一阶就是两阶,而背包中物体体积不一,因此根据i列状态转移,然后同楼梯一样,楼梯只需遍历阶数,而背包遍历i和j最后得到答案。(因此无法理解背包就去类比楼梯吧)
不过只是有一点注意(注释处)
#include
#include
#include
#include
using namespace std;
long long volume[1005];
long long value[1005];
long long dp[1005][1005];
int main()
{
 int T;
 cin >> T;
 while (T--)
 {
  memset(dp, 0, sizeof(dp));
  memset(value, 0, sizeof(value));
  memset(volume, 0, sizeof(volume));
  int N, V;
  cin >> N >> V;
  for (int i = 1; i <= N; i++)
   cin >> value[i];
  for (int i = 1; i <= N; i++)
   cin >> volume[i];
  for (int i = 1; i <= N; i++)
  for (int j = 0; j <= V; j++)             //j不能初始化为1
  {
   if (j >= volume[i])
    dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - volume[i]] + value[i]);
   else
    dp[i][j] = dp[i - 1][j];
  }
   cout << dp[N][V] << endl;
 }
 return 0;
}
0 0