// UVa 540 - Team Queue
import java.util.*;
public class Main {
private static class TeamQueue<E, T> {
private Map<E, T> memberToTeam = new HashMap<>();
private Map<T, Queue<E>> teamToQueue = new HashMap<>();
private Queue<T> teamOrder = new LinkedList<>();
void addMember(E member, T teamIndex) {
memberToTeam.put(member, teamIndex);
}
void enqueue(E member) {
if (!memberToTeam.containsKey(member)) throw new IllegalArgumentException();
T team = memberToTeam.get(member);
if (!teamToQueue.containsKey(team)) {
teamToQueue.put(team, new LinkedList<>());
}
if (teamToQueue.get(team).isEmpty()) {
teamOrder.add(team);
}
teamToQueue.get(team).add(member);
}
E dequeue() {
E member = teamToQueue.get(teamOrder.peek()).poll();
while (!teamOrder.isEmpty() && teamToQueue.get(teamOrder.peek()).isEmpty())
teamOrder.poll();
return member;
}
}
public static void main(String[] args) {
int scenario = 0;
try (Scanner scanner = new Scanner(System.in)) {
while (true) {
int numberOfTeams = scanner.nextInt();
if (numberOfTeams == 0)
break;
scenario++;
System.out.println("Scenario #" + scenario);
TeamQueue<Integer, Integer> teamQueue = new TeamQueue<>();
for (int teamIndex = 0; teamIndex < numberOfTeams; teamIndex++) {
int teamSize = scanner.nextInt();
for (int j = 0; j < teamSize; j++) {
int member = scanner.nextInt();
teamQueue.addMember(member, teamIndex);
}
}
String instruction = scanner.next();
while (!"STOP".equals(instruction)) {
if ("ENQUEUE".equals(instruction)) {
int member = scanner.nextInt();
teamQueue.enqueue(member);
} else {
System.out.println(teamQueue.dequeue());
}
instruction = scanner.next();
}
System.out.println();
}
}
}
}
Tuesday, September 24, 2019
UVa 540 - Team Queue
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment