• 문제 링크
10451번: 순열 사이클
1부터 N까지 정수 N개로 이루어진 순열을 나타내는 방법은 여러 가지가 있다. 예를 들어, 8개의 수로 이루어진 순열 (3, 2, 7, 8, 1, 4, 5, 6)을 배열을 이용해 표현하면 \(\begin{pmatrix} 1 & 2 &3&4&5&6&7&8 \\ 3
www.acmicpc.net
• 풀이 코드
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
public class Main {
static int[] arr;
static boolean[] visit;
public static void main(String[] args) throws IOException {
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringBuilder sb = new StringBuilder();
int t = read();
while (t-- > 0) {
int n = read();
arr = new int[n];
visit = new boolean[n];
for (int i = 0; i < n; i++) arr[i] = read() - 1;
int cnt = 0;
for (int i = 0; i < n; i++) {
if (!visit[i]) {
dfs(i);
cnt++;
}
}
sb.append(cnt).append("\n");
}
bw.write(sb.toString());
bw.flush();
}
private static void dfs(int src) {
if (visit[src]) return;
visit[src] = true;
dfs(arr[src]);
}
private static int read() throws IOException {
int c, n = System.in.read() & 15;
while ((c = System.in.read()) > 32) n = (n << 3) + (n << 1) + (c & 15);
return n;
}
}
'Problem Solving > Baekjoon' 카테고리의 다른 글
[백준] 20914 QWERTY 자판 - Graph Theory / Java (0) | 2024.03.07 |
---|---|
[백준] 6179 Oh Those Rollers - Graph Theory / Java (0) | 2024.03.06 |
[백준] 9897 Lamp - Data Structure / Java (0) | 2024.03.04 |
[백준] 6325 Definite Values - Data Structure / Java (0) | 2024.03.03 |
[백준] 6474 Palindromes - Data Structure / Java (0) | 2024.03.02 |
댓글