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