Saturday, January 21, 2012

0-1 Knapsack (DP) UVA-10130

#include<stdio.h>
#define max( a, b ) ( a > b ? a : b )
#define CSE 1005


int N,MW,C[CSE][CSE],Vi[CSE],Wi[CSE];


int Knapsack()
{
int i,w;
for (i=0;i<=N ;i++) C[i][0] = 0;
for (w=0;w<=MW;w++) C[0][w] = 0;


for (i=1;i<=N;i++)
{
for (w=0;w<=MW;w++)
{
if (Wi[i] > w) C[i][w] = C[i-1][w];
else C[i][w] = max(C[i-1][w] , C[i-1][w-Wi[i]]+Vi[i]);
}
}
return C[N][MW];
}
int main()
{
int sum,MW_num,i,y,tcase;


scanf("%d",&tcase);
while(tcase--)
{
scanf("%d",&N);
for(i=1;i<=N;i++)
scanf("%d%d",&Vi[i],&Wi[i]);


sum=0;
scanf("%d",&MW_num);
while(MW_num--)
{
scanf("%d",&MW);
y=Knapsack();
sum+=y;
}
printf("%d\n",sum);
}
return 0;
}
/*
Input:
2
3
72 17
44 23
31 24
1
26
6
64 26
85 22
52 4
99 18
39 13
54 9
4
23
20
20
26
Output:
72
514
*/

2 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Uncle Variable gular name gula ektu bodhogommo kore dile valo hoto..:\\

    ReplyDelete