|
| 1 | +```java |
| 2 | +import java.util.*; |
| 3 | +import java.io.*; |
| 4 | +public class Main{ |
| 5 | + public static void main(String[] args) throws Exception{ |
| 6 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 7 | + BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); |
| 8 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 9 | + long N = Long.parseLong(st.nextToken()); |
| 10 | + long K = Integer.parseInt(st.nextToken()); |
| 11 | + long Q = Integer.parseInt(st.nextToken()); |
| 12 | + |
| 13 | + for(int i=0;i<Q;i++){ |
| 14 | + st = new StringTokenizer(br.readLine()); |
| 15 | + long x = Long.parseLong(st.nextToken()); |
| 16 | + long y = Long.parseLong(st.nextToken()); |
| 17 | + long start = Math.min(x,y); //start를 작은걸로 |
| 18 | + long end = Math.max(x,y); //end를 큰걸로 고정 |
| 19 | + if(K == 1){ |
| 20 | + bw.write((end-start)+"\n"); |
| 21 | + continue; |
| 22 | + } |
| 23 | + long startdepth = findDepth(start,K); |
| 24 | + long enddepth = findDepth(end,K); |
| 25 | + long depthDiff = enddepth - startdepth; |
| 26 | + long dist = 0; |
| 27 | + for(int j=0;j<depthDiff;j++){ |
| 28 | + end = findParent(end, K); |
| 29 | + dist++; |
| 30 | + } |
| 31 | + while(start!=end){ |
| 32 | + start = findParent(start, K); |
| 33 | + end = findParent(end, K); |
| 34 | + dist+=2; |
| 35 | + } |
| 36 | + bw.write(dist+"\n"); |
| 37 | + } |
| 38 | + bw.flush(); |
| 39 | + } |
| 40 | + public static long findDepth(long x,long K){ |
| 41 | + long finder = 1; |
| 42 | + long depth = 1; |
| 43 | + while(x > finder){ |
| 44 | + finder *= K; |
| 45 | + finder += 1; |
| 46 | + depth++; |
| 47 | + } |
| 48 | + return depth; |
| 49 | + } |
| 50 | + public static long findParent(long x,long K){ |
| 51 | + if(x%K==0 || x%K==1){ |
| 52 | + return x/K; |
| 53 | + }else{ |
| 54 | + return x/K + 1; |
| 55 | + } |
| 56 | + } |
| 57 | +} |
| 58 | +``` |
0 commit comments