Mirineo

10. Poisonous Plants#1001

Jan 18th, 2021
151
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.96 KB | None | 0 0
  1. package StacksAndQueues.Exercise;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.IOException;
  5. import java.io.InputStreamReader;
  6. import java.util.ArrayDeque;
  7. import java.util.Arrays;
  8. import java.util.stream.Collectors;
  9.  
  10.  
  11. public class PoisonousPlants {
  12. private static void reverse(ArrayDeque<Integer> queue)
  13. {
  14. ArrayDeque<Integer> s = new ArrayDeque(); //create a stack
  15.  
  16. //while the queue is not empty
  17. while(!queue.isEmpty())
  18. { //add the elements of the queue onto a stack
  19. s.push(queue.poll());
  20. }
  21.  
  22. //while the stack is not empty
  23. while(!s.isEmpty())
  24. { //add the elements in the stack back to the queue
  25. queue.offer(s.pop());
  26. }
  27.  
  28. }
  29.  
  30. public static void main(String[] args) throws IOException {
  31.  
  32. BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
  33. int numberOfPlants = Integer.parseInt(reader.readLine());
  34. ArrayDeque<Integer> pesticidePerPlant = Arrays.stream(reader.readLine()
  35. .split("\\s+"))
  36. .map(Integer::parseInt)
  37. .collect(Collectors.toCollection(ArrayDeque::new));
  38.  
  39. reverse(pesticidePerPlant);
  40. boolean areDying = true;
  41. int days = 0;
  42. while (areDying){
  43. int currentSize = pesticidePerPlant.size();
  44. for (int i = 0; i < currentSize - 1; i++) {
  45. int currentIndex = pesticidePerPlant.peek();
  46. if(pesticidePerPlant.poll() <= pesticidePerPlant.peek()){
  47. pesticidePerPlant.offer(currentIndex);
  48. }
  49. }
  50.  
  51. if(pesticidePerPlant.size() > 2)pesticidePerPlant.offer(pesticidePerPlant.poll());
  52.  
  53. if(currentSize - pesticidePerPlant.size() == 0) {
  54. areDying = false;
  55. }else {
  56. days++;
  57. }
  58. }
  59.  
  60. System.out.println(days);
  61. }
  62. }
  63.  
  64.  
  65.  
Advertisement
Add Comment
Please, Sign In to add comment