[๋ฐฑ์ค€/python] 11724๋ฒˆ : ์—ฐ๊ฒฐ ์š”์†Œ์˜ ๊ฐœ์ˆ˜

2021. 8. 23. 18:29

๋ฌธ์ œ

๋ฐฉํ–ฅ ์—†๋Š” ๊ทธ๋ž˜ํ”„๊ฐ€ ์ฃผ์–ด์กŒ์„ ๋•Œ, ์—ฐ๊ฒฐ ์š”์†Œ (Connected Component)์˜ ๊ฐœ์ˆ˜๋ฅผ ๊ตฌํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค.

 

์ž…๋ ฅ

์ฒซ์งธ ์ค„์— ์ •์ ์˜ ๊ฐœ์ˆ˜ N๊ณผ ๊ฐ„์„ ์˜ ๊ฐœ์ˆ˜ M์ด ์ฃผ์–ด์ง„๋‹ค. (1 ≤ N ≤ 1,000, 0 ≤ M ≤ N×(N-1)/2) ๋‘˜์งธ ์ค„๋ถ€ํ„ฐ M๊ฐœ์˜ ์ค„์— ๊ฐ„์„ ์˜ ์–‘ ๋์  u์™€ v๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. (1 ≤ u, v ≤ N, u ≠ v) ๊ฐ™์€ ๊ฐ„์„ ์€ ํ•œ ๋ฒˆ๋งŒ ์ฃผ์–ด์ง„๋‹ค.

 

์ถœ๋ ฅ

์ฒซ์งธ ์ค„์— ์—ฐ๊ฒฐ ์š”์†Œ์˜ ๊ฐœ์ˆ˜๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.

 

์ •๋‹ต

import sys
input = sys.stdin.readline

N, M = map(int, input().split())
dic = {n:[] for n in range(1, N+1)}

for _ in range(M):
    u, v = map(int, input().split())
    dic[u].append(v)
    dic[v].append(u)

visited = []
def dfs(n):
    stack = [n]
    while stack:
        num = stack.pop()
        if num not in visited:
            visited.append(num)
            stack.extend(dic[num])
    return 1

answer = 0
for i in range(1, N+1):
    if len(visited) == N:
        break
    if i not in visited:
        answer += dfs(i)

print(answer)

 

728x90

BELATED ARTICLES

more