https://www.acmicpc.net/problem/2668
코드
def solution(N, graph):
visited = [False] * (N + 1)
result = []
def dfs(start):
stack, path = [start], []
while stack:
node = stack.pop()
if visited[node]: # 싸이클 발견
if node in path:
idx = path.index(node)
result.extend(path[idx:])
return
visited[node] = True
path.append(node)
stack.append(graph[node])
return
for i in range(1, N):
if not visited[i]:
dfs(i)
result = sorted(set(result))
print(len(result))
for num in result:
print(num)
return
# 입력
N = int(input())
graph = [ 0 ]
for _ in range(N):
graph.append(int(input()))
solution(N, graph)
풀이
사이클을 찾는 문제입니다.
저 같은 경우 DFS로 사이클을 찾아가면서
마지막에 정렬을 해줬습니다.
728x90
'백준 > 골드' 카테고리의 다른 글
택배 배송 5972번 - Python, 다익스트라(Dijkstra) (0) | 2025.02.07 |
---|---|
음악프로그램(2623) - Python, 위상정렬 (0) | 2025.01.24 |
피자판매 2632번 - Pyton, 부분합 (0) | 2025.01.01 |
백준 > 2931번 > 가스관 - JAVA (0) | 2023.08.29 |
백준 > 17471번 > 게리멘더링 - JAVA (1) | 2023.04.12 |