algorithm/Algorithm-Core
리스트에서 순환되는 점 찾기
근데 어렵다.
public class Main { private static int[] s; private static int[] p; private static int n; private static int T; private static boolean[] vis; private static boolean[] fin; private static int cnt; public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = null; T = Integer.parseInt(br.readLine().trim()); for (int t = 1; t <= T; t++) { n = Integer.parseInt(br.readLine().trim()); st = new StringTokenizer(br.readLine().trim()); s = new int[n + 1]; p = new int[n + 1]; vis = new boolean[n + 1]; fin = new boolean[n + 1]; cnt = 0; for (int i = 1; i <= n; i++) { s[i] = Integer.parseInt(st.nextToken()); } for (int i = 1; i <= n; i++) { if (!vis[i]) { dfs(i); } } System.out.println(n - cnt); } } private static void dfs(int idx) { vis[idx] = true; int next = s[idx]; if (!vis[next]) { p[next] = idx; dfs(next); } else { if (!fin[next]) { cycle(idx, s[idx]); } } fin[idx] = true; } private static void cycle(int idx, int next) { cnt++; if (idx == next) return; cycle(p[idx], next); }
}
* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.