fork download
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3.  
  4. int unboundedKnapsack(int *W, int wLen, int *V, int cap) {
  5. int *K=(int*)malloc(sizeof(int)*(cap+1));
  6. int w, i, j;
  7. int best=0;
  8. K[0]=0;
  9. for(w=1;w<=cap;w++)
  10. {
  11. for(i=0;i<wLen;i++)
  12. {
  13. if(w>=W[i])
  14. {
  15. best=(K[w-W[i]]+V[i]>best)?(K[w-W[i]]+V[i]):best;
  16. }
  17. }
  18. K[w]=best;
  19. }
  20. return K[cap];
  21. }
  22.  
  23. int main()
  24. {
  25. int i,j,v[500],c[500],n,k=0,m,no,t;
  26. scanf("%d",&t);
  27. while(t--)
  28. {
  29. k=0;
  30. scanf("%d",&n);
  31. for(i=0;i<n;i++)
  32. {
  33. scanf("%d",&c[i]);
  34. v[i]=i+1;
  35. }
  36. //scanf("%d",&k);
  37. printf("%d\n",(unboundedKnapsack(v,n,c,n)));
  38. }
  39. return 0;
  40. }
Success #stdin #stdout 0s 2384KB
stdin
2
4
2 3 4 5
5
2 5 9 8 10
stdout
8
14