Home BOJ. Composite Function And Query (17435)
Post
Cancel

BOJ. Composite Function And Query (17435)

[Link] https://www.acmicpc.net/problem/17435


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
import java.util.*;
import java.io.*;

public class Main {
	static BufferedReader br;
	static StringBuilder sb = new StringBuilder();
	public static void main(String[] args) throws IOException {
		br = new BufferedReader(new InputStreamReader(System.in));
		int[] arr;
		int m = toi(br.readLine());
		int[] y = new int[m + 1];
		int n = (int)(Math.log(m) / Math.log(2));
		// int[][] sparse = new int[m + 1][11];
		ArrayList<ArrayList<Integer>> sparse = new ArrayList<>();
		sparse.add(new ArrayList<>());

		arr = getArr();
		for(int i = 0; i < m; i++) {
			ArrayList<Integer> tmp = new ArrayList<>();
			tmp.add(arr[i]);
			sparse.add(tmp);
		}

		int query = toi(br.readLine());

		for(int i = 0; i < query; i++) {
			arr = getArr();
			int num = arr[0], x = arr[1];
			int digit = 0, ans = x;

			while(num > 0) {
				if((num & 1) == 1) {
					if(sparse.get(1).size() <= digit) {
						for(int j = sparse.get(1).size() ; j <= digit ; j++) {
							for(int idx = 1; idx <= m; idx++) {
								sparse.get(idx).add(sparse.get(sparse.get(idx).get(j - 1)).get(j - 1));
							}
						}
					}
					ans = sparse.get(ans).get(digit);
				}
				num >>= 1;
				digit++;
			}
			sb.append(ans).append("\n");
		}
		print(sb);
	}

	static int toi(String s) { return Integer.parseInt(s); }
	static long tol(String s) { return Long.parseLong(s); }
	static String[] getLine() throws IOException { return br.readLine().split(" "); }
	static int[] getArr() throws IOException { return Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray(); }
	static <T> void print(T s) { System.out.print(s); }
	static <T> void println(T s) { System.out.println(s); }
}
This post is licensed under CC BY 4.0 by the author.