fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. class Interval {
  8. int start, end;
  9. String train, platform;
  10.  
  11. Interval(int s, int e, String t, String p) {
  12. start = s;
  13. end = e;
  14. train = t;
  15. platform = p;
  16. }
  17. }
  18.  
  19. class TrainPlatformManager {
  20.  
  21. Map<String, TreeMap<Integer, Interval>> platformMap = new HashMap<>();
  22. Map<String, TreeMap<Integer, Interval>> trainMap = new HashMap<>();
  23.  
  24. // Assign train to platform
  25. public boolean assignTrain(String train, String platform, int start, int end) {
  26. if (start >= end) return false;
  27.  
  28. platformMap.putIfAbsent(platform, new TreeMap<>());
  29. TreeMap<Integer, Interval> pm = platformMap.get(platform);
  30.  
  31. // conflict check
  32. Map.Entry<Integer, Interval> floor = pm.floorEntry(start);
  33. if (floor != null && floor.getValue().end > start) return false;
  34.  
  35. Map.Entry<Integer, Interval> ceil = pm.ceilingEntry(start);
  36. if (ceil != null && end > ceil.getKey()) return false;
  37.  
  38. Interval interval = new Interval(start, end, train, platform);
  39. pm.put(start, interval);
  40.  
  41. trainMap.putIfAbsent(train, new TreeMap<>());
  42. trainMap.get(train).put(start, interval);
  43.  
  44. return true;
  45. }
  46.  
  47. // Platform + time -> train
  48. public String getTrainAtPlatform(String platform, int time) {
  49. TreeMap<Integer, Interval> pm = platformMap.get(platform);
  50. if (pm == null) return null;
  51.  
  52. Map.Entry<Integer, Interval> e = pm.floorEntry(time);
  53. if (e == null || time >= e.getValue().end) return null;
  54.  
  55. return e.getValue().train;
  56. }
  57.  
  58. // Train + time -> platform
  59. public String getPlatformForTrain(String train, int time) {
  60. TreeMap<Integer, Interval> tm = trainMap.get(train);
  61. if (tm == null) return null;
  62.  
  63. Map.Entry<Integer, Interval> e = tm.floorEntry(time);
  64. if (e == null || time >= e.getValue().end) return null;
  65.  
  66. return e.getValue().platform;
  67. }
  68. }
  69. /* Name of the class has to be "Main" only if the class is public. */
  70. class Ideone
  71. {
  72. public static void main (String[] args) throws java.lang.Exception
  73. {
  74. // your code goes here
  75. }
  76. }
Success #stdin #stdout 0.09s 52592KB
stdin
Standard input is empty
stdout
Standard output is empty