0-1背包问题

 1 int N = 3;
 2 int V = 5;
 3 int C[4] = {0,1,2,3};
 4 int W[4] = {0,60,100,120};
 5 int f[N][V];
 6 //memset(f,0,sizeof(int)*N*V);
 7 for(int i=0;i<=V;i++)
 8 f[0][i] = 0;
 9 for(int i=1;i<=N;i++)
10 {
11 f[i][0] = 0;
12 for(int j = 1;j<=V;j++)
13 {
14 if(j<C[i])
15 f[i][j] = f[i-1][j];
16 else
17 f[i][j] = (f[i-1][j] > (f[i-1][j-C[i]]+W[i])? f[i-1][j]:(f[i-1][j-C[i]]+W[i]));
18 }
19 }
20 printf("value:weight: ");
21 for(int i=1;i<4;i++)
22 {
23 printf("%d:%d ",C[i],W[i]);
24 }
25 printf("\nThe final value is %d\n",f[N][V]);

 

posted @ 2018-11-24 19:47  执著的追求  阅读(194)  评论(0编辑  收藏  举报