7-6 完全背包问题
有 N 种物品和一个容量是 V 的背包,每种物品都有无限件可用。
第 i 种物品的体积是 vi,价值是 wi。
求解将哪些物品装入背包,可使这些物品的总体积不超过背包容量,且总价值最大。 输出最大价值。
输入格式
第一行两个整数,N,V,用空格隔开,分别表示物品种数和背包容积。
接下来有 N 行,每行两个整数 vi,wi,用空格隔开,分别表示第 i 种物品的体积和价值。
输出格式
输出一个整数,表示最大价值。
数据范围
0<N,V≤1000 0<vi,wi≤1000
输入样例
4 5
1 2
2 4
3 4
4 5
输出样例:
10
完全背包递归求解,注意大的在前,小的在后,为了解决这类
3 5
1 2
2 4
3 3
代码如下:
#include <stdio.h>
#include <stdlib.h>
int n,w;
struct node
{
int weight;
int value;
}a[1010];
int vis[1010][1010];
int max(int a,int b)
{
return a>=b?a:b;
}
int find(int x,int w)
{
if(x>=n)
return 0;
else
{
if(a[x].weight<=w)
{
if(vis[x][w]!=0)
return vis[x][w];
int l=find(x+1,w-a[x].weight*(w/a[x].weight))+a[x].value*(w/a[x].weight);
int r=find(x+1,w);
return vis[x][w]=max(l,r);
}
else
return vis[x][w]=find(x+1,w);
}
}
int sort(struct node *a, struct node *b)
{
if((* (struct node *)a).weight != ( * (struct node *)b).weight)
return ( * (struct node * )a).weight > ( * (struct node * )b).weight ? -1 : 1;
else return (* (struct node * )a).value >( * (struct node * )b).value ? 1 : -1;
}
int main()
{
scanf("%d%d",&n,&w);
for(int i=0;i<n;i++)
{
int w,v;
scanf("%d%d",&w,&v);
a[i].value=v;
a[i].weight=w;
}
qsort(a,n,sizeof(struct node),sort);
int max=find(0,w);
printf("%d",max);
return 0;
}
202110181853一