https://www.acmicpc.net/problem/10451
์ฒ์์ ๊ทธ๋ํ๋ฅผ ๋ง๋ค์ด์ ์ฌ๊ท๋ฅผ ํ๋๋ฐ ์๊ฐ ์ ํ์ผ๋ก ์คํจ!
์คํจํ ์ฝ๋
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
'Algorithms > Algorithms' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
์ ์ฐพ๊ธฐ (๋ฐฑ์ค 1920๋ฒ, ํด์) (0) | 2021.11.04 |
---|---|
1๋ก๋ง๋ค๊ธฐ (๋ฐฑ์ค1463) (0) | 2021.10.13 |
์ฐ๊ฒฐ์์์๊ฐ์ (๋ฐฑ์ค 11724) (0) | 2021.10.12 |
์ด๋ถ ๊ทธ๋ํ (๋ฐฑ์ค 1707) (0) | 2021.10.08 |
[๋ฐ์ดํฐ ๊ตฌ์กฐ] ๋ฐฐ์ด(Array)์ ์ฐ๊ฒฐ๋ฆฌ์คํธ(Linked List)๋ก ๋ฆฌ์คํธ ์ถ์์๋ฃํ ๊ตฌํ (with C) (0) | 2021.04.16 |