-
Notifications
You must be signed in to change notification settings - Fork 0
/
Task2.java
97 lines (74 loc) · 2.29 KB
/
Task2.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/* Kornilov Nikita, M3102, 16.04.2021 */
package Sem2.Lab12;
import java.io.*;
import java.util.*;
public class Task2 {
BufferedReader br;
StringTokenizer in;
PrintWriter out;
public static void main(String[] args) {
new Task2().run();
}
public String nextToken() throws IOException {
while (in == null || !in.hasMoreTokens()) {
String inputString = br.readLine();
if (inputString != null) {
in = new StringTokenizer(inputString);
}
else {
return null;
}
}
return in.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
public void solve() throws IOException {
int n = nextInt();
int[] inputArray = new int[n];
int[] parent = new int[n];
for (int i = 0; i < n; i++) {
inputArray[i] = nextInt();
}
TreeMap<Integer, Integer> map = new TreeMap<>(); // key - value, value - index
for (int i = 0; i < n; i++) {
if (map.containsKey(inputArray[i])) {
continue;
}
map.put(inputArray[i], i);
if (map.lastKey() != inputArray[i]) {
map.remove(map.higherKey(inputArray[i]));
}
if (map.lowerKey(inputArray[i]) != null) {
parent[i] = map.lowerEntry(inputArray[i]).getValue();
}
else {
parent[i] = map.get(inputArray[i]);
}
}
Stack<Integer> lis = new Stack<>();
Iterator<Integer> iterator = map.descendingKeySet().iterator();
int index = map.lastEntry().getValue();
while (iterator.hasNext()) {
lis.push(inputArray[index]);
index = parent[index];
iterator.next();
}
out.println(lis.size());
while (!lis.isEmpty()) {
out.print(lis.pop() + " ");
}
}
public void run() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
}