Skip to content

Commit 14ae6b4

Browse files
authored
Merge pull request #521 from AlgorithmWithGod/khj20006
[20250722] BOJ / P5 / 이진 검색 트리 / 권혁준
2 parents 13a985d + 969cea5 commit 14ae6b4

File tree

1 file changed

+105
-0
lines changed

1 file changed

+105
-0
lines changed
Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
```java
2+
import java.util.*;
3+
import java.io.*;
4+
5+
class IOController {
6+
BufferedReader br;
7+
BufferedWriter bw;
8+
StringTokenizer st;
9+
10+
public IOController() {
11+
br = new BufferedReader(new InputStreamReader(System.in));
12+
bw = new BufferedWriter(new OutputStreamWriter(System.out));
13+
st = new StringTokenizer("");
14+
}
15+
16+
String nextLine() throws Exception {
17+
String line = br.readLine();
18+
st = new StringTokenizer(line);
19+
return line;
20+
}
21+
22+
String nextToken() throws Exception {
23+
while (!st.hasMoreTokens()) nextLine();
24+
return st.nextToken();
25+
}
26+
27+
int nextInt() throws Exception {
28+
return Integer.parseInt(nextToken());
29+
}
30+
31+
long nextLong() throws Exception {
32+
return Long.parseLong(nextToken());
33+
}
34+
35+
double nextDouble() throws Exception {
36+
return Double.parseDouble(nextToken());
37+
}
38+
39+
void close() throws Exception {
40+
bw.flush();
41+
bw.close();
42+
}
43+
44+
void write(String content) throws Exception {
45+
bw.write(content);
46+
}
47+
48+
}
49+
50+
public class Main {
51+
52+
static IOController io;
53+
54+
//
55+
56+
static final int INF = (int)1e9 + 7;
57+
58+
static int N;
59+
static int[] dep, idx;
60+
static TreeSet<Integer> set;
61+
62+
public static void main(String[] args) throws Exception {
63+
64+
io = new IOController();
65+
66+
init();
67+
solve();
68+
69+
io.close();
70+
71+
}
72+
73+
public static void init() throws Exception {
74+
75+
N = io.nextInt();
76+
dep = new int[N];
77+
idx = new int[N];
78+
set = new TreeSet<>();
79+
80+
}
81+
82+
static void solve() throws Exception {
83+
84+
set.add(io.nextInt());
85+
long ans = 1;
86+
for(int i=1;i<N;i++) {
87+
int a = io.nextInt();
88+
int right = set.higher(a) == null ? -1 : set.higher(a);
89+
int left = set.lower(a) == null ? -1 : set.lower(a);
90+
if(right == -1) dep[a] = dep[left]+1;
91+
else if(left == -1) dep[a] = dep[right]+1;
92+
else {
93+
if(idx[left] > idx[right]) dep[a] = dep[left]+1;
94+
else dep[a] = dep[right]+1;
95+
}
96+
ans += dep[a]+1;
97+
idx[a] = i;
98+
set.add(a);
99+
}
100+
io.write(ans + "\n");
101+
102+
}
103+
104+
}
105+
```

0 commit comments

Comments
 (0)