Skip to content

Commit 3b6d582

Browse files
authored
Merge pull request #104 from AlgorithmWithGod/khj20006
[20250213] BOJ / G3 / K진 트리 / 권혁준
2 parents 511daf5 + 6d707f6 commit 3b6d582

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
```java
2+
3+
import java.util.*;
4+
import java.io.*;
5+
6+
7+
class Main {
8+
9+
// IO field
10+
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
11+
static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
12+
static StringTokenizer st;
13+
14+
static void nextLine() throws Exception {st = new StringTokenizer(br.readLine());}
15+
static int nextInt() {return Integer.parseInt(st.nextToken());}
16+
static long nextLong() {return Long.parseLong(st.nextToken());}
17+
static void bwEnd() throws Exception {bw.flush();bw.close();}
18+
19+
// Additional field
20+
static long N, K, Q;
21+
22+
public static void main(String[] args) throws Exception {
23+
24+
ready();
25+
solve();
26+
27+
bwEnd();
28+
}
29+
30+
static void ready() throws Exception{
31+
32+
nextLine();
33+
N = nextLong();
34+
K = nextLong();
35+
Q = nextLong();
36+
37+
}
38+
39+
static void solve() throws Exception{
40+
41+
while(Q-- > 0) {
42+
nextLine();
43+
long x = nextLong(), y = nextLong();
44+
bw.write(dist(x-1,y-1) + "\n");
45+
}
46+
47+
}
48+
49+
static long dist(long x, long y) throws Exception{
50+
if(K == 1) return Math.abs(x-y);
51+
List<Long> X = find(x), Y = find(y);
52+
int i = X.size()-1, j = Y.size()-1;
53+
54+
while(i>=0 && j>=0 && X.get(i).equals(Y.get(j))){
55+
i--;
56+
j--;
57+
}
58+
return i+j+2;
59+
}
60+
61+
static List<Long> find(long x){
62+
List<Long> result = new ArrayList<>();
63+
64+
result.add(x);
65+
while(x > 0) {
66+
x = (x-1)/K;
67+
result.add(x);
68+
}
69+
return result;
70+
}
71+
72+
}
73+
74+
```

0 commit comments

Comments
 (0)