fork download
  1. //package spoj;
  2.  
  3.  
  4. import java.util.Arrays;
  5. import java.io.*;
  6. class PARTY
  7. {
  8. public static void main(String args[])
  9. throws IOException
  10. {
  11. String str="";
  12. while(!(str=br.readLine().trim()).equals("0 0"))
  13. {
  14. String in[]=str.trim().split(" ");
  15. int W=Integer.parseInt(in[0]);
  16. int n=Integer.parseInt(in[1]);
  17. //now making the store table.
  18. int arr_v[]=new int[n+1];
  19. int arr_w[]=new int[n+1];
  20. arr_v[0]=arr_w[0]=0;
  21. for(int i=1;i<=n;i++)
  22. {
  23. String in2[]=br.readLine().trim().split(" ");//12 3 cost fun
  24. arr_w[i]=Integer.parseInt(in2[0]);
  25. arr_v[i]=Integer.parseInt(in2[1]);
  26. }
  27. //store table complete.
  28. //now main work
  29. int V[][]=new int[n+1][W+1];
  30. Arrays.fill(V[0],0);
  31.  
  32. for(int i=1;i<=n;i++)
  33. {
  34. for(int w=0;w<=W;w++)
  35. {
  36. if((arr_w[i]<w) && (arr_v[i]+V[i-1][w-arr_w[i]])>V[i-1][w])
  37. V[i][w]=arr_v[i]+V[i-1][w-arr_w[i]];
  38. else
  39. V[i][w]=V[i-1][w];
  40. }
  41. }
  42. /////
  43.  
  44. int k=W,i=n;
  45. int sum=0;
  46. while(i>0 && k>0)
  47. {
  48. if(V[i][k]!=V[i-1][k])
  49. {
  50. //System.out.print(arr_w[i]+" "+arr_v[i]+"\n");
  51. sum+=arr_w[i];
  52. i--;
  53. k-=arr_w[i];
  54. }
  55. else
  56. i--;
  57. }
  58. /////
  59. System.out.println(sum+" "+V[n][W]);
  60. String blank=br.readLine();
  61. }
  62. //pw.flush();
  63. }
  64. }
Success #stdin #stdout 0.07s 380160KB
stdin
50 10
12 3
15 8
16 9
16 6
10 2
21 9
18 4
12 4
17 8
18 9 

50 10
13 8
19 10
16 8
12 9
10 2
12 8
13 5
15 5
11 7
16 2

0 0
stdout
49 26
36 32