File tree Expand file tree Collapse file tree 1 file changed +65
-0
lines changed
Expand file tree Collapse file tree 1 file changed +65
-0
lines changed Original file line number Diff line number Diff line change 1+ ``` java
2+ import java.io.* ;
3+ import java.util.* ;
4+
5+ public class Main {
6+ static int n;
7+ static int [] arr;
8+ static boolean [] visited;
9+ static int answer = 0 ;
10+ static int [] indegree;
11+
12+ public static void main (String [] args ) throws IOException {
13+ BufferedReader br = new BufferedReader (new InputStreamReader (System . in));
14+ int t = Integer . parseInt(br. readLine());
15+ while (t-- > 0 ){
16+ n = Integer . parseInt(br. readLine());
17+ arr = new int [n + 1 ];
18+ visited = new boolean [n + 1 ];
19+ StringTokenizer st = new StringTokenizer (br. readLine());
20+ for (int i = 1 ; i <= n; i++ ) {
21+ arr[i] = Integer . parseInt(st. nextToken());
22+ }
23+
24+ for (int i = 1 ; i <= n; i++ ) {
25+ if (! visited[i]) {
26+ dfs(i);
27+ }
28+ }
29+
30+ System . out. println(n - answer);
31+ }
32+
33+ }
34+
35+ static void dfs (int start ) {
36+ Map<Integer , Integer > map = new HashMap<> ();
37+ List<Integer > path = new ArrayList<> ();
38+
39+ int cur = start;
40+ while (true ) {
41+ if (visited[cur]) {
42+ break ;
43+ }
44+
45+ visited[cur] = true ;
46+ map. put(cur, path. size());
47+ path. add(cur);
48+ int next = arr[cur];
49+ // 다음 학생이 범위를 벗어나면 즉시 종료(ㅣ사이클 없으니까)
50+ if (next < 1 || next > n) break ;
51+
52+ if (! map. containsKey(next)) {
53+ cur = next;
54+ continue ;
55+ } else {
56+ // 사이클 발견
57+ int idx = map. get(next);
58+ answer += path. size() - idx;
59+ break ;
60+ }
61+ }
62+ }
63+ }
64+
65+ ```
You can’t perform that action at this time.
0 commit comments