티스토리 뷰

728x90
반응형

문제

https://www.acmicpc.net/problem/10451

 

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 collections

t = int(input())
queue = collections.deque()

def bfs(index):
    queue.append(index)
    while queue:
        cur = queue.popleft()
        visited[cur] = True
        if visited[graph[cur]] == False:
            visited[graph[cur]] = True
            queue.append(graph[cur])

for i in range(t):
    n = int(input())
    graph = [0]+list(map(int, input().split()))
    visited = [0 for _ in range(n+1)]
    count = 0
    for j in range(1, n+1):
        if visited[j] == False:
            bfs(j)
            count += 1
    print(count)

visited로 방문체크를 해줘서 모든 정점노드들을 for문으로 돌아 방문하지 않은 정점일 경우 bfs를 실행한다.

 

즉, bfs 실행 횟수가 사이클이 생긴 횟수와 같아진다.

반응형
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31