fork(2) download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. List<MyTime> myTimeList = new ArrayList<MyTime>();
  13. myTimeList.add(new MyTime(7, 9));
  14. myTimeList.add(new MyTime(9, 15));
  15. myTimeList.add(new MyTime(2, 6));
  16. myTimeList.add(new MyTime(1, 5));
  17. myTimeList.add(new MyTime(2, 4));
  18. myTimeList.add(new MyTime(10, 12));
  19.  
  20. Collections.sort(myTimeList);
  21.  
  22. System.out.println(myTimeList.size());
  23.  
  24. Stack s = new Stack();
  25. Stack e = new Stack();
  26. s.push(0);
  27. e.push(0);
  28. for (MyTime time : myTimeList)
  29. {
  30. System.out.println(time.getStart() + " " + time.getEnd());
  31. if (time.getStart() > time.getEnd())
  32. throw new Exception("The time is incorrect.");
  33.  
  34. if (time.getStart() > (int)e.peek()) //没有交集
  35. {
  36. s.push(time.getStart());
  37. e.push(time.getEnd());
  38. }
  39. else if (time.getEnd() > (int)e.peek()) //有部分交集,取并集
  40. {
  41. e.pop();
  42. e.push(time.getEnd());
  43. }
  44. //else {} //完全被覆盖
  45. }
  46.  
  47. int total = 0;
  48. while (!s.empty())
  49. {
  50. System.out.println(s.peek() + " ~ " + e.peek());
  51. total += (int)e.pop() - (int)s.pop();
  52. }
  53. System.out.println("Total: " + total);
  54. }
  55. }
  56.  
  57. class MyTime implements Comparable<MyTime>
  58. {
  59. private int start;
  60. private int end;
  61. MyTime(){}
  62. MyTime(int start, int end)
  63. {
  64. this.start = start;
  65. this.end = end;
  66. }
  67. public int getStart()
  68. {
  69. return start;
  70. }
  71. public int getEnd()
  72. {
  73. return end;
  74. }
  75. public int compareTo(MyTime other)
  76. {
  77. if (start == other.start)
  78. {
  79. return other.end - end;
  80. }
  81. return start - other.start;
  82. }
  83. }
Success #stdin #stdout 0.08s 380160KB
stdin
Standard input is empty
stdout
6
1 5
2 6
2 4
7 9
9 15
10 12
7 ~ 15
1 ~ 6
0 ~ 0
Total: 13