#include <stdio.h> #define W 1000 #define N 1000 typedef struct data ...{ int vaule; int weight; }goods; int returnmax(int a, int b) ...{ return (a > b ? a : b); } int KNAPSACK(goods *P, int a, int s) ...{ int V[N][W]; int i,j,mv; for(i =0; i < a; i++) V[i][0] =0; for(j =0; j < s; j++) V[0][j] =0; for(i =1; i <= a; i++) for(j =1; j <= s; j++) ......{ V[i][j] = V[i -1][j]; if(P[i].weight <= j) V[i][j] = returnmax(V[i][j],V[i -1][j - P[i].weight] + P[i].vaule); } mv = V[a][s]; return mv; } int main() ...{ int mostvalue,amount,size,i; goods A[N]; printf("Input how much the goods have: "); scanf("%d",&amount); printf("Input the size of the bag: "); scanf("%d",&size); printf("Input the data of the goods: "); for(i =0; i < amount; i++) scanf("%d %d",&A[i].vaule,&A[i].weight); mostvalue = KNAPSACK(A,amount,size); printf("%d",mostvalue); return0; }
还有一种纯粹用数组解决的方案,避免了结构体的效率底下,思路是一样的 代码如下:
#include<iostream> #define GOODNUM 5 usingnamespace std; int main() ...{ int good[GOODNUM][2]=...{...{4,6},...{5,2},...{6,3},...{7,7},...{8,5}};//good[i][0]:size||good[i][1]:value int i,j,size,weight; int v[GOODNUM+1][1000]; cout<<"please input the bag's size"<<endl; cin>>size; for(i=0;i<=GOODNUM;i++) v[i][0]=0; for(i=0;i<=size;i++) v[0][i]=0; for(i=1;i<=GOODNUM;i++) for(j=1;j<=size;j++)...{ v[i][j]=v[i-1][j]; if(good[i-1][0]<=j) if((v[i-1][j-good[i-1][0]]+good[i-1][1])>v[i][j]) v[i][j]=v[i-1][j-good[i-1][0]]+good[i-1][1]; } cout<<v[GOODNUM][size]<<endl; }