好久没做题了,也是自己太懒了,然后随着性子歇了几天。
大概学了一下背包问题,按照学长给的文章
链接: link.
背包问题是在价值最大情况下尽量装满的情况的算法
题目大致如下:
Many years ago , in Teddy’s hometown there was a man who was called “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 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 ?
Input
The first line contain a integer T , the number of cases.
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.OutputOne integer per line representing the maximum of the total value (this number will be less than 2
31).
题目大意就是在尽量装满的情况下价值最大
1行为案例数
2行第一个为骨头数,第二个为背包容积
3行为骨头的质量,4行是骨头的价值,与三行的一一对应。
Sample Input
1
5 10
1 2 3 4 5
5 4 3 2 1
Sample Output
14
(解释,二行背包容量是10,选择了前四块,1+2+3+4=10,价值是5+4+3+2=14,所以输出14)
这题先在数组初始化上翻车,之后是算法上花了好久才搞明白
记得dp时的顺序就行
一维数组版本的答案:(忘了结构体初始化了,不然想用结构体初始化的)
#include <stdio.h>
#include <string.h>
long long num[1005],pay[1005],dp[1005];
long long max(int a,int b){
return a>b?a:b;
}
int main(){
int t,n,v,i,m;//按题意走。
scanf("%d",&t);
while(t--){
memset(num,0,sizeof(num));
memset(pay,0,sizeof(pay));
memset(dp,0,sizeof(dp));//千万记得清空数组!切记切记!
scanf("%d %d",&n,&v);
for(i=1;i<=n;i++) scanf("%lld",&num[i]);
for(i=1;i<=n;i++) scanf("%lld",&pay[i]);
for(i=1;i<=n;i++){
for(m=v;m>=pay[i];m--){//这个算法先死记硬背的
dp[m]=max(dp[m],dp[m-pay[i]]+num[i]);
}
}
printf("%lld\n",dp[v]);
}
}