[BaekJoon] 17435 합성함수와 쿼리 (Java)

오태호·2023년 7월 5일
0

백준 알고리즘

목록 보기
269/395
post-thumbnail

1.  문제 링크

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

2.  문제


3.  소스코드

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Main {
    private final static int LOG = 18;

    static int m, Q;
    static int[][] dp;
    static int[][] queries;

    static void input() {
        Reader scanner = new Reader();

        m = scanner.nextInt();
        dp = new int[LOG + 1][m + 1];

        for(int idx = 1; idx <= m; idx++)
            dp[0][idx] = scanner.nextInt();

        Q = scanner.nextInt();
        queries = new int[Q][2];

        for(int idx = 0; idx < Q; idx++) {
            int n = scanner.nextInt(), x = scanner.nextInt();
            queries[idx][0] = n;
            queries[idx][1] = x;
        }
    }

    static void solution() {
        for(int row = 1; row <= LOG; row++) {
            for(int col = 1; col <= m; col++)
                dp[row][col] = dp[row - 1][dp[row - 1][col]];
        }

        for(int idx = 0; idx < Q; idx++) {
            for(int row = LOG; row >= 0; row--) {
                int cur = (1 << row);
                if(queries[idx][0] >= cur) {
                    queries[idx][1] = dp[row][queries[idx][1]];
                    queries[idx][0] -= cur;
                    if(queries[idx][0] == 0) break;
                }
            }
            System.out.println(queries[idx][1]);
        }
    }

    public static void main(String[] args) {
        input();
        solution();
    }

    static class Reader {
        BufferedReader br;
        StringTokenizer st;

        public Reader() {
            br = new BufferedReader(new InputStreamReader(System.in));
        }

        String next() {
            while(st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            return st.nextToken();
        }

        int nextInt() {
            return Integer.parseInt(next());
        }
    }
}
profile
자바, 웹 개발을 열심히 공부하고 있습니다!

0개의 댓글