大家好,又见面了,我是全栈君。
The bone collector had a big bag with a volume of V ,and along his trip of collecting there are a lot of bones , obviously , different bone has different value and different volume, now given the each bone’s value along his trip , can you calculate out the maximum of the total value the bone collector can get ?

Followed by T cases , each case three lines , the first line contain two integer N , V, (N <= 1000 , V <= 1000 )representing the number of bones and the volume of his bag. And the second line contain N integers representing the value of each bone. The third line contain N integers representing the volume of each bone.
31).
1 5 10 1 2 3 4 5 5 4 3 2 1
14
for(i=1;i<=n;i++)
for(j=v;j>=c[i];j--)
liu[j]=max(liu[j],liu[j-c[i]]+w[i]);
这三行就是核心。就像背包九讲里面说的,这个状态转移方程很重要,一定要理解,它联系了上一个状态和这一个状态,所以叫做状态转移方程!
!!!
!!
for(i=1;i<=n;i++)
{
for(j=v;j>=c[i];j--)
{
liu[j]=max(liu[j],liu[j-c[i]]+w[i]);
}
for(k=1;k<=v;k++)
printf("%d ",liu[k]);
printf("\n");
}
我们以题目给的数据为例,执行结果例如以下:


!!!
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<iostream>
using namespace std;
int main()
{
int i,j,k;
int t,n,m,v;
int liu[1006],c[1006],w[1006];
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&v);
for(i=1;i<=n;i++)
scanf("%d",&w[i]);
for(i=1;i<=n;i++)
scanf("%d",&c[i]);
memset(liu,0,sizeof(liu));
for(i=1;i<=n;i++)
{
for(j=v;j>=c[i];j--)
{
liu[j]=max(liu[j],liu[j-c[i]]+w[i]);
}
for(k=1;k<=v;k++)
printf("%d ",liu[k]);
printf("\n");
}
printf("%d\n",liu[v]);
}
return 0;
}
写代码能力有限,如有编程爱好者发现bug,还请指出,不胜感激!
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/115497.html原文链接:https://javaforall.net
