-
Notifications
You must be signed in to change notification settings - Fork 2
/
BusNumbers.java
71 lines (56 loc) · 1.86 KB
/
BusNumbers.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
/*
Problem: https://open.kattis.com/problems/busnumbers
Author: Adrian Reithaug
Submitted: June 14th, 2017
Time: 0.11s / 1.00s
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class BusNumbers {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int numBuses = Integer.parseInt(reader.readLine());
List<Integer> buses = new ArrayList<>();
String[] busNumbers = reader.readLine().split(" ");
for (int i = 0; i < numBuses; i++) {
buses.add(Integer.parseInt(busNumbers[i]));
}
if (numBuses == 1) {
System.out.println(buses.get(0));
return;
}
Collections.sort(buses);
int start = 0, numAdjacent = 1;
boolean adjacent = true;
for (int i = 1; i < numBuses; i++) {
if (buses.get(i - 1) == (buses.get(i) - 1)) {
numAdjacent++;
} else {
adjacent = false;
}
boolean lastBus = (i == numBuses - 1);
if (lastBus || !adjacent) {
if (numAdjacent > 2) {
System.out.print(buses.get(start) + "-");
if (!adjacent) {
System.out.print(buses.get(i - 1) + " ");
}
} else {
for (int j = start; j < i; j++) {
System.out.print(buses.get(j) + " ");
}
}
start = i;
numAdjacent = 1;
adjacent = true;
}
if (lastBus) {
System.out.println(buses.get(i));
}
}
}
}