Advertisement
Guest User

Untitled

a guest
Jun 16th, 2019
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.63 KB | None | 0 0
  1. import java.io.BufferedReader;
  2. import java.io.InputStreamReader;
  3. import java.util.Scanner;
  4.  
  5. public class Main{
  6. public static void main(String[] args) {
  7. BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  8. Scanner in = new Scanner(br);
  9. int casos = in.nextInt();
  10. while (casos > 0) {
  11. int nobj = in.nextInt();
  12. int[] W = new int[nobj + 1];
  13. int[] V = new int[nobj + 1];
  14. for (int i = 0; i < nobj; i++) {
  15. V[i + 1] = in.nextInt();
  16. W[i + 1] = in.nextInt();
  17. }
  18. int familiar = in.nextInt();
  19. int total = 0;
  20. while (familiar > 0) {
  21. int limite = in.nextInt();
  22. int[] peso = new int[limite + 1];
  23. for (int j = 0; j < limite; j++) {
  24. peso[j + 1] = j + 1;
  25. }
  26. int[][] matrix = new int[W.length][peso.length];
  27. total = total + KnapSack(W.length, peso.length, W, V, matrix);
  28. familiar--;
  29. }
  30. System.out.println(total);
  31. casos--;
  32. }
  33. }
  34.  
  35. static int KnapSack(int n1, int n2, int[] W, int[] V, int[][] matrix) {
  36. for (int i = 1; i < n1; i++) {
  37. for (int j = 1; j < n2; j++) {
  38. if (W[i] <= j) {
  39. matrix[i][j] = Math.max(
  40. matrix[i - 1][j], V[i] + matrix[i - 1][j - W[i]]);
  41. } else
  42. matrix[i][j] = matrix[i - 1][j];
  43. }
  44. }
  45. return matrix[n1-1][n2-1];
  46. }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement