[백준] PS/Java [실랜디]

[백준 3182] 한동이는 공부가 하기 싫어! - JAVA

SH3542 2025. 3. 30. 18:22

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

 

재귀x dfs

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

class Main {

  public static void main(String[] args) throws IOException {

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    int N = Integer.parseInt(br.readLine());

    int a[] = new int[N + 1];

    for (int i = 1; i <= N; i++) {
      a[i] = Integer.parseInt(br.readLine());
    }

    int max = 0;
    PriorityQueue<Integer> q = new PriorityQueue<>();

    for (int i = 1; i <= N; i++) {

      int cnt = 1;
      int next = a[i];

      boolean vst[] = new boolean[N + 1];
      vst[i] = true;

      while (!vst[next]) {
        vst[next] = true;
        next = a[next];
        cnt++;
      }

      if (cnt > max) {
        max = cnt;
        q.clear();
        q.offer(i);
      } else if (cnt == max) {
        q.offer(i);
      }
    }

    System.out.println(q.peek());
  }
}