Skip to content

Commit 8998cb2

Browse files
authored
Merge pull request #350 from AlgorithmWithGod/suyeun84
[20250613] BOJ / G3 / 텀 프로젝트 / 김수연
2 parents a7b261d + 15dbc83 commit 8998cb2

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
```java
2+
import java.io.*;
3+
import java.util.*;
4+
5+
public class boj9466 {
6+
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
7+
static StringTokenizer st;
8+
static void nextLine() throws Exception {st = new StringTokenizer(br.readLine());}
9+
static int nextInt() {return Integer.parseInt(st.nextToken());}
10+
11+
static int N, cycle;
12+
static int[] point;
13+
static boolean[] check, visited;
14+
public static void main(String[] args) throws Exception {
15+
nextLine();
16+
int T = nextInt();
17+
18+
for (int tc = 0; tc < T; tc++) {
19+
nextLine();
20+
N = nextInt();
21+
nextLine();
22+
point = new int[N+1];
23+
for (int i = 1; i <= N; i++) point[i] = nextInt();
24+
cycle = 0;
25+
check = new boolean[N+1];
26+
visited = new boolean[N+1];
27+
28+
for (int i = 1; i <= N; i++) {
29+
if (check[i]) continue;
30+
dfs(i);
31+
}
32+
System.out.println(N - cycle);
33+
}
34+
35+
}
36+
static void dfs(int idx) {
37+
if (check[idx]) return;
38+
if (visited[idx]) {
39+
check[idx] = true;
40+
cycle++;
41+
}
42+
visited[idx] = true;
43+
dfs(point[idx]);
44+
check[idx] = true;
45+
visited[idx] = false;
46+
}
47+
}
48+
```

0 commit comments

Comments
 (0)