241018 합성함수와 쿼리

Jongleee·2024년 10월 18일
0

TIL

목록 보기
707/737
public static void main(String[] args) throws IOException {
	BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

	int numElements = Integer.parseInt(br.readLine());
	int[][] ancestors = new int[20][numElements + 1];
	StringTokenizer st = new StringTokenizer(br.readLine());

	for (int i = 1; i <= numElements; i++) {
		ancestors[0][i] = Integer.parseInt(st.nextToken());
	}

	for (int i = 1; i < 20; i++) {
		for (int j = 1; j <= numElements; j++) {
			ancestors[i][j] = ancestors[i - 1][ancestors[i - 1][j]];
		}
	}

	int numQueries = Integer.parseInt(br.readLine());
	StringBuilder result = new StringBuilder();

	while (numQueries-- > 0) {
		st = new StringTokenizer(br.readLine());
		int steps = Integer.parseInt(st.nextToken());
		int startNode = Integer.parseInt(st.nextToken());

		for (int i = 0; steps > 0; i++) {
			if ((steps & 1) > 0) {
				startNode = ancestors[i][startNode];
			}
			steps >>= 1;
		}
		result.append(startNode).append("\n");
	}

	System.out.println(result.toString());
	br.close();
}

출처:https://www.acmicpc.net/problem/17435

0개의 댓글