Advertisement
Guest User

gifts.java

a guest
Oct 28th, 2016
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.18 KB | None | 0 0
  1. import java.util.*;
  2. import java.io.*;
  3.  
  4. public class gifts {
  5.  
  6. public static void main(String[] args) throws IOException {
  7. Scanner in = new Scanner(new File("gifts.in"));
  8. int n = in.nextInt(); // # cows
  9. int b = in.nextInt(); // budgets
  10.  
  11. Cow[] cows = new Cow[n];
  12. for(int i=0; i<n; i++) {
  13. cows[i] = new Cow(in.nextInt(), in.nextInt());
  14. }
  15. in.close();
  16.  
  17. Arrays.sort(cows);
  18. //System.out.println(Arrays.toString(cows));
  19.  
  20. long totalCost = 0;
  21. int totalGifts = 0;
  22. for(int i=0; i<cows.length; i++) {
  23. totalCost += cows[i].cost;
  24. if(totalCost > b) {
  25. totalCost -= cows[i].cost;
  26. totalGifts = i;
  27. break;
  28. }
  29. }
  30.  
  31. int max = totalGifts;
  32. for(int i=0; i<totalGifts; i++) {
  33. long temp = totalCost;
  34. temp -= cows[i].price / 2;
  35. if(temp + cows[totalGifts].cost <= b) {
  36. max++;
  37. break;
  38. }
  39. }
  40.  
  41. if(max == totalGifts) {
  42. for(int i=totalGifts; i<cows.length; i++) {
  43. long newTotalCost = totalCost + cows[i].cost - (cows[i].price / 2);
  44. if(newTotalCost <= b) {
  45. max++;
  46. break;
  47. }
  48. }
  49. }
  50.  
  51.  
  52. PrintWriter out = new PrintWriter(new File("gifts.out"));
  53. System.out.print(max);
  54. out.println(max);
  55. out.close();
  56.  
  57. }
  58.  
  59. // Cow() {} no need for default constructors
  60.  
  61. static class Cow implements Comparable<Cow> {
  62. int price, shipping, cost;
  63.  
  64. Cow(int price, int shipping) {
  65. this.price = price;
  66. this.shipping = shipping;
  67. this.cost = price + shipping;
  68. }
  69.  
  70. public int compareTo(Cow other) {
  71. // returns positive number if this Cow should be counted as greater than the other cow
  72. // returns negative number if this Cow should be counted as less
  73. // returns 0 it this Cow is counted as equal to the other
  74.  
  75. return this.cost - other.cost;
  76. }
  77.  
  78. public String toString() {
  79. return "Cow(" + cost + "," + price + "," + shipping + ")";
  80. }
  81. }
  82.  
  83. }
  84.  
  85. /** Analysis:
  86. * 1) sort by total price
  87. * 2) loop through from the left (low end) and count how many fit before going over budget
  88. * 3) loop through each cow, applying discount, (could be any one) and check if that allows that cow or another cow to be fit into the budget where it wasn't before
  89. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement