|
| 1 | +package Arrays; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.Collections; |
| 5 | +import java.util.List; |
| 6 | + |
| 7 | +/* |
| 8 | +https://www.geeksforgeeks.org/job-sequencing-using-disjoint-set-union/?ref=lbp |
| 9 | + */ |
| 10 | +public class JobScheduling { |
| 11 | + static class Job { |
| 12 | + char id; |
| 13 | + int profit; |
| 14 | + int deadline; |
| 15 | + |
| 16 | + Job(char a, int d, int p) { |
| 17 | + this.id = a; |
| 18 | + this.profit = p; |
| 19 | + this.deadline = d; |
| 20 | + } |
| 21 | + |
| 22 | + @Override |
| 23 | + public String toString() { |
| 24 | + return "Job{" + |
| 25 | + "id=" + id + |
| 26 | + ", profit=" + profit + |
| 27 | + ", deadline=" + deadline + |
| 28 | + '}'; |
| 29 | + } |
| 30 | + } |
| 31 | + |
| 32 | + static class DisjointSet { |
| 33 | + int[] parent; |
| 34 | + DisjointSet(int length) { |
| 35 | + this.parent = new int[length + 1]; |
| 36 | + |
| 37 | + for (var i = 0; i < parent.length; i++) { |
| 38 | + parent[i] = i; |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + int find(int slot) { |
| 43 | + if (slot == parent[slot]) |
| 44 | + return slot; |
| 45 | + |
| 46 | + return parent[slot] = find(parent[slot]); |
| 47 | + } |
| 48 | + |
| 49 | + void merge(int par, int child) { |
| 50 | + this.parent[child] = par; |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + int maxTimeSlot(List<Job> jobs) { |
| 55 | + int ans = Integer.MIN_VALUE; |
| 56 | + for (var job : jobs) { |
| 57 | + ans = Math.max(ans, job.deadline); |
| 58 | + } |
| 59 | + |
| 60 | + return ans; |
| 61 | + } |
| 62 | + |
| 63 | + |
| 64 | + void scheduleJobs(List<Job> jobs) { |
| 65 | + Collections.sort(jobs, (j1, j2) -> {return (j1.profit > j2.profit) ? -1 : 1;}); |
| 66 | + int maxSlot = maxTimeSlot(jobs); |
| 67 | + DisjointSet disjointSet = new DisjointSet(maxSlot); |
| 68 | + |
| 69 | + for (var job : jobs) { |
| 70 | +// System.out.println(" job is " + job); |
| 71 | + int availableSlot = disjointSet.find(job.deadline); |
| 72 | +// System.out.println("available slot is " + availableSlot); |
| 73 | + if (availableSlot > 0) { |
| 74 | + disjointSet.merge(disjointSet.find(availableSlot - 1), availableSlot); |
| 75 | + System.out.print(job + " "); |
| 76 | + } |
| 77 | + } |
| 78 | + } |
| 79 | + |
| 80 | + public static void main(String[] args) { |
| 81 | + ArrayList<Job> arr =new ArrayList<Job>(); |
| 82 | + arr.add(new Job('a',2,100)); |
| 83 | + arr.add(new Job('b',1,19)); |
| 84 | + arr.add(new Job('c',2,27)); |
| 85 | + arr.add(new Job('d',1,25)); |
| 86 | + arr.add(new Job('e',3,15)); |
| 87 | + |
| 88 | + JobScheduling jobScheduling = |
| 89 | + new JobScheduling(); |
| 90 | + jobScheduling.scheduleJobs(arr); |
| 91 | + } |
| 92 | +} |
0 commit comments