-
Notifications
You must be signed in to change notification settings - Fork 0
/
lifeguards.java
80 lines (64 loc) · 1.98 KB
/
lifeguards.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/*
ID: helena.6
LANG: JAVA
TASK: lifeguards
*/
import java.io.*;
import java.util.Arrays;
import java.util.Comparator;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class lifeguards {
static int n;
public static void main(String[] args) throws IOException {
BufferedReader f = new BufferedReader(new FileReader("lifeguards.in"));
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("lifeguards.out")));
n = Integer.parseInt(f.readLine());
Interval[] timeIntervals = new Interval[2*n];
for (int i = 0; i < n; i++) {
StringTokenizer st = new StringTokenizer(f.readLine());
timeIntervals[2*i] = new Interval(Integer.parseInt(st.nextToken()), i);
timeIntervals[2*i+1] = new Interval(Integer.parseInt(st.nextToken()), i);
}
Arrays.sort(timeIntervals, new Comparator<Interval>() {
@Override
public int compare(Interval x, Interval y) {
return x.getTime() - y.getTime();
}
});
TreeSet<Integer> set = new TreeSet<Integer>(); //treeset to keep intervals sorted
int fullTime = 0; //total amount of time covered by all cows together, none fired
int[] alone = new int[n]; //amount of time they cover that isn't covered by anyone else
int prev = 0;
for (Interval i: timeIntervals) {
if (set.size() == 1)
alone[set.first()] += (i.getTime() - prev);
if (!set.isEmpty())
fullTime += i.getTime() - prev;
if (set.contains(i.getIndex())) //start and end have been handled. remove it
set.remove(i.getIndex());
else
set.add(i.getIndex());
prev = i.getTime();
}
int maxTime = 0;
for (int i: alone)
maxTime = Math.max(maxTime, fullTime - i);
out.println(maxTime);
out.close();
}
}
class Interval {
private int time;
private int index;
public Interval(int time, int index) {
this.time = time;
this.index = index;
}
public int getTime() {
return time;
}
public int getIndex() {
return index;
}
}