Algorithms/Algorithms
μμ΄ μ¬μ΄ν΄ (λ°±μ€ 10451)
ν±μ €
2021. 10. 12. 17:00
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 sys
sys.setrecursionlimit(1000000)
input = sys.stdin.readline
t = int(input())
def dfs(v):
visited[v] = 1
for i in range(n + 1):
if visited[i] == 0 and graph[v][i] == 1:
dfs(i)
for i in range(t):
n = int(input())
visited = [0 for j in range(n + 1)]
graph = [[0 for k in range(n + 1)] for m in range(n + 1)]
m = list(map(int, input().split()))
for a, b in enumerate(m):
graph[a + 1][b] = 1
graph[b][a + 1] = 1
cnt = 0
for j in range(1, n + 1):
if visited[j] == 0:
dfs(j)
cnt += 1
print(cnt)
μΌμ°¨μ λ°°μ΄λ‘ μ½κ² ν΄κ²°νκΈ°
import sys
sys.setrecursionlimit(1000000)
input = sys.stdin.readline
t = int(input())
def dfs(v):
visited[v] = 1
next = m[v]
if visited[next] == 0:
dfs(next)
for i in range(t):
n = int(input())
visited = [0] * (n + 1)
m = [0] + list(map(int, input().split()))
cnt = 0
for j in range(1, n + 1):
if visited[j] == 0:
dfs(j)
cnt += 1
print(cnt)
m = [0] + list(map(int, input().split()))
python 리μ€νΈ λνκΈ°,,, κΈ°λ³Έμ μΈ κ² κΉλ¨Ήμ§ λ§κΈ°,,,
728x90