Algorithm/DFS&BFS
9466λ²/DFS ν νλ‘μ νΈ/νμ΄μ¬
μ νΈλ
2024. 9. 29. 15:17
π λ¬Έμ
https://www.acmicpc.net/problem/9466
πμ€νκ²°κ³Ό
π λ΄κ° μκ°ν νμ΄
μ¬μ΄ν΄μ΄ λ§λ€μ΄μ§λ νμμ΄ νμ΄ λ§λ€μ΄μ§.
π» λ΅μ
import sys
sys.setrecursionlimit(10 ** 6)
input = sys.stdin.readline
def dfs(x,result):
visited[x] = True
# μ¬μ΄ν΄μ μ΄λ£¨λ ν νμΈνκΈ° μν΄
cycle.append(x)
number = arr[x]
# λ°©λ¬Έκ°λ₯ν κ³³μ΄ λλ¬λμ§
if visited[number]:
# μ¬μ΄ν΄ κ°λ₯ μ¬λΆ
if number in cycle:
# μ¬μ΄ν΄ λλ κ΅¬κ° λΆν°λ§ ν μ΄λ£Έ
result += cycle[cycle.index(number):]
return
else:
dfs(number,result)
# ν
μ€νΈμΌμ΄μ€μΈ int(input())λ§νΌ μν
for _ in range(int(input())):
# n : νμ μ
n = int(input())
# νμλ€μ λ²νΈ
arr = [0] +list(map(int,input().split()))
visited = [False for _ in range(n+1)]
result =[]
for i in range(1,n+1):
# λ°©λ¬Έ μν κ³³μ΄λ©΄
if not visited[i]:
# cycleνλ ¬ μμ±ν΄μ
cycle = []
# dfsν¨μ λλ¦Ό
dfs(i,result)
# νμ μλ μ¬λμ
print(n-len(result))
βΊοΈ λλμ
DFS/BFS μ΄λ €μ
μ°Έκ³ μλ£ λ΄μΌ ꡬνκ°λ₯
π μ°Έκ³
https://oh2279.tistory.com/138
[λ°±μ€/νμ΄μ¬] 9466λ² ν νλ‘μ νΈ
https://www.acmicpc.net/problem/9466 9466λ²: ν νλ‘μ νΈ μ΄λ² κ°μνκΈ°μ 'λ¬Έμ ν΄κ²°' κ°μλ₯Ό μ μ²ν νμλ€μ ν νλ‘μ νΈλ₯Ό μνν΄μΌ νλ€. νλ‘μ νΈ νμ μμλ μ νμ΄ μλ€. μ¬μ§μ΄ λͺ¨λ νμλ€μ΄
oh2279.tistory.com
https://www.youtube.com/watch?v=yPuow6aACvE