첫째 줄
M개의 줄
// NOTE: 입력
2
8
3 2 7 8 1 4 5 6
10
2 1 3 4 5 6 7 9 10 8
// NOTE: 출력
3
7
// NOTE: 입력
2 -------------------------- 테스트 케이스 T
8 -------------------------- 🔥 Case1의 크기 N
3 2 7 8 1 4 5 6 ------------ Case1의 순열 데이터
10 ------------------------- 🔥 Case2의 크기 N
2 1 3 4 5 6 7 9 10 8 ------- Case2의 순열 데이터
Array
로 생성graph[from_node] = to_node
push
로 인접노드 설정const makeGraph = (n, permutation) => {
const _graph = [0];
permutation.trim().split(' ').forEach(to => {
_graph.push(+to);
});
return _graph;
};
return
visitedArr[node] = true
로 설정const dfs = (node, visitedArr, graphArr) => {
if (visitedArr[node]) return;
visitedArr[node] = true;
dfs(graphArr[node], visitedArr, graphArr);
};
const makeGraph = (n, permutation) => {
const _graph = [0];
permutation.trim().split(' ').forEach(to => {
_graph.push(+to);
});
return _graph;
};
const dfs = (node, visitedArr, graphArr) => {
if (visitedArr[node]) return;
visitedArr[node] = true;
dfs(graphArr[node], visitedArr, graphArr);
};
const solution = () => {
let [T,..._inputs] = require('fs')
.readFileSync('dev/stdin')
.toString()
.trim()
.split(/\n/);
T = +T;
while(T--) {
const N = +_inputs.shift();
const _graphArr = makeGraph(N, _inputs.shift());
const _visitedArr = new Array(N + 1).fill(false);
let _count = 0;
for (let i = 1; i <= N; i++) {
if (_visitedArr[i]) continue;
dfs(i, _visitedArr, _graphArr);
_count += 1;
}
console.log(_count);
}
};
solution();