Advertisement
VladNitu

PQ

Dec 13th, 2022
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.72 KB | None | 0 0
  1. package weblab;
  2.  
  3. import java.util.*;
  4.  
  5.  
  6. class Task implements Comparable<Task> {
  7. int start, end;
  8.  
  9. public Task(int start, int end) {
  10. this.start = start;
  11. this.end = end;
  12. }
  13.  
  14. @Override
  15. public int compareTo(Task o) {
  16. return Integer.compare(this.start, o.start);
  17. }
  18. }
  19.  
  20. class Solution {
  21.  
  22.  
  23. /**
  24. * @param n number of researchers
  25. * @param m number of minutes after which workstations lock themselves
  26. * @param start start times of jobs 1 through n. NB: you should ignore start[0]
  27. * @param duration duration of jobs 1 through n. NB: you should ignore duration[0]
  28. * @return the number of unlocks that can be saved.
  29. */
  30. public static int solve(int n, int m, int[] start, int[] duration) {
  31. Task[] tasks = new Task[n];
  32. for (int i = 1; i <= n; ++i)
  33. tasks[i-1] = new Task(start[i], start[i] + duration[i]);
  34.  
  35. Arrays.sort(tasks); // increasing by start time
  36.  
  37.  
  38. PriorityQueue<Integer> pq = new PriorityQueue<>();
  39. int locks = 0;
  40.  
  41. for (Task task: tasks) {
  42.  
  43. if (pq.isEmpty()) {
  44. pq.add(task.end);
  45. locks ++;
  46. continue;
  47. }
  48.  
  49. while (!pq.isEmpty() && task.start > pq.peek() + m) // machine won't be used anymore
  50. pq.poll();
  51.  
  52. if (pq.isEmpty()) {
  53. pq.add(task.end);
  54. locks ++;
  55. }
  56. else
  57. if (task.start >= pq.peek())
  58. {
  59. pq.poll();
  60. pq.add(task.end);
  61. }
  62. else {
  63. pq.add(task.end);
  64. locks ++;
  65. }
  66.  
  67.  
  68. }
  69.  
  70. return n - locks;
  71.  
  72. }
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement