[백준] 10451번: 순열 사이클

jooo·2023년 2월 20일
0

백준

목록 보기
30/35
post-thumbnail

💻 문제 - S3


👉 제출 코드

import sys
sys.setrecursionlimit(10 ** 6)
input = sys.stdin.readline

def dfs(v):
    visited[v] = 1
    next_node = permutation[v]
    if not visited[next_node]:
        dfs(next_node)

for _ in range(int(input())):
    N = int(input())
    permutation = [0] + list(map(int, input().split()))
    visited = [0] * (N+1)
    cnt = 0
    for i in range(1, N+1):
        if not visited[i]:
            dfs(i)
            cnt += 1
    print(cnt)
  • 10 ** 6만큼 충분한 재귀 깊이를 주어 오류를 예방한다.
  • dfs로 순열 사이클을 탐색한다. 탐색할 때마다 순열 사이클의 개수를 더한다.
profile
조금씩, 꾸준히, 자주

0개의 댓글