很基础的0-1背包。。。
#include<stdio.h>
#include<memory.h>#define MAX(a,b) (a>b?a:b)
int c[1005],n[1005],v[1005],i,j,t,N,V;
void Zero_One(int cost, int weight, int m) // 0-1背包, 逆序
{
int i;
for(i=m;i>=cost;i--)
c[i]=MAX(c[i],c[i-cost]+weight);
}
int main()
{
while(scanf("%d",&t)!=EOF)
{
while(t--){
scanf("%d%ld",&N,&V);
memset(c,0,sizeof(c));
for(i=1;i<=N;i++) scanf("%d",&v[i]);
for(i=1;i<=N;i++) scanf("%ld",&n[i]);
for(i=1;i<=N;i++){
Zero_One(n[i],v[i],V);
}
printf("%ld\n",c[V]);
}
}
system("pause");
return 0;
}

本文介绍了一种解决0-1背包问题的基本方法,包括使用逆序进行优化的0-1背包函数Zero_One,通过读取输入数据并计算最大价值来实现背包问题的最优解。
467

被折叠的 条评论
为什么被折叠?



