We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
/*
* Create the Student and Priorities classes here.
/
import java.util.;
class Student implements Comparable {
private int id;
private String name;
private double cgpa;
public Student(int id, String name, double cgpa) {
this.id = id;
this.name = name;
this.cgpa = cgpa;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public double getCGPA() {
return cgpa;
}
@Override
public int compareTo(Student other) {
if (Double.compare(other.cgpa, this.cgpa) != 0) {
return Double.compare(other.cgpa, this.cgpa); // Higher CGPA comes first
} else if (!this.name.equals(other.name)) {
return this.name.compareTo(other.name); // Sort by name alphabetically
} else {
return Integer.compare(this.id, other.id); // Sort by ID if names are the same
}
}
}
class Priorities {
private PriorityQueue pq;
public Priorities() {
pq = new PriorityQueue<>();
}
public List<Student> getStudents(List<String> events) {
int idCounter = 1; // Initialize ID counter to generate unique IDs
for (String event : events) {
String[] parts = event.split(" ");
String operation = parts[0];
if (operation.equals("ENTER")) {
String name = parts[1];
double cgpa = Double.parseDouble(parts[2]);
int id = Integer.parseInt(parts[3]); // Read ID from the event
pq.add(new Student(id, name, cgpa));
} else if (operation.equals("SERVED")) {
pq.poll(); // Remove the highest priority student
}
}
List<Student> result = new ArrayList<>();
while (!pq.isEmpty()) {
result.add(pq.poll()); // Collect remaining students
}
return result;
}
}
public class Solution {
private final static Scanner scan = new Scanner(System.in);
private final static Priorities priorities = new Priorities();
public static void main(String[] args) {
int totalEvents = Integer.parseInt(scan.nextLine());
List<String> events = new ArrayList<>();
while (totalEvents-- != 0) {
String event = scan.nextLine();
events.add(event);
}
List<Student> students = priorities.getStudents(events);
if (students.isEmpty()) {
System.out.println("EMPTY");
} else {
for (Student st: students) {
System.out.println(st.getName());
}
}
}
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Java Priority Queue
You are viewing a single comment's thread. Return to all comments →
import java.util.ArrayList; import java.util.List; import java.util.Scanner;
/* * Create the Student and Priorities classes here. / import java.util.;
class Student implements Comparable { private int id; private String name; private double cgpa;
}
class Priorities { private PriorityQueue pq;
}
public class Solution { private final static Scanner scan = new Scanner(System.in); private final static Priorities priorities = new Priorities();
}