Advertisement
Guest User

Untitled

a guest
Feb 25th, 2018
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.77 KB | None | 0 0
  1. import java.io.*;
  2. import java.util.StringTokenizer;
  3.  
  4. public class Test {
  5. public static void main(String[] args) {
  6. InputReader reader = new InputReader();
  7. int stomachCapacity = reader.readInt();
  8. int numberOfFoods = reader.readInt();
  9. String[] foodName = new String[numberOfFoods + 1];
  10. int[] foodWeight = new int[numberOfFoods + 1];
  11. int[] foodTaste = new int[numberOfFoods + 1];
  12. for (int i = 1; i <= numberOfFoods; i++) {
  13. foodName[i] = reader.readLine();
  14. foodWeight[i] = reader.readInt();
  15. foodTaste[i] = reader.readInt();
  16. }
  17.  
  18. int[][] value = new int[numberOfFoods + 1][stomachCapacity + 1];
  19. for (int r = 1; r <= numberOfFoods; r++) {
  20. for (int c = 1; c <= stomachCapacity; c++) {
  21. if (foodWeight[r] <= c) {
  22. value[r][c] = getMax(value[r - 1][c], value[r - 1][c - foodWeight[r]] + foodTaste[r]);
  23. } else {
  24. value[r][c] = value[r - 1][c];
  25. }
  26. }
  27. }
  28.  
  29. int[] foodEaten = backtrace(value, foodWeight, stomachCapacity, numberOfFoods);
  30.  
  31. System.out.println(value[numberOfFoods] [stomachCapacity]);
  32. for (int i = foodEaten.length - 1; i >= 1; i--) {
  33. if (foodEaten[i] == 1) {
  34. System.out.println(foodName[i]);
  35. }
  36. }
  37. }
  38.  
  39. private static int[] backtrace(int[][] value, int[] foodWeight, int stomachCapacity, int numberOfFoods) {
  40. int[] foodEaten = new int[numberOfFoods + 1];
  41. int r = numberOfFoods;
  42. int c = stomachCapacity;
  43. while (r > 0 && c > 0) {
  44. if (value[r][c] != value[r - 1][c]) {
  45. foodEaten[r] = 1;
  46. c = c - foodWeight[r];
  47. }
  48. r--;
  49. }
  50. return foodEaten;
  51. }
  52.  
  53. private static int getMax(int a, int b) {
  54. if (a > b) {
  55. return a;
  56. } else {
  57. return b;
  58. }
  59. }
  60.  
  61. static class InputReader {
  62. private BufferedReader br;
  63. private StringTokenizer st;
  64.  
  65. InputReader() {
  66. try {
  67. br = new BufferedReader(new InputStreamReader(System.in));
  68. } catch (Exception e) {
  69. e.printStackTrace();
  70. }
  71. }
  72.  
  73. String readLine() {
  74. while (st == null || !st.hasMoreTokens()) {
  75. try {
  76. st = new StringTokenizer(br.readLine());
  77. } catch (IOException e) {
  78. e.printStackTrace();
  79. }
  80. }
  81. return st.nextToken();
  82. }
  83.  
  84. int readInt() {
  85. return Integer.parseInt(readLine());
  86. }
  87. }
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement