๐Ÿ’ก๋ฌธ์ œ ๋ถ„์„ ์š”์•ฝ

์‹œ๊ฐ„ ์ œํ•œ ๋ฉ”๋ชจ๋ฆฌ ์ œํ•œ
3์ดˆ 512MB

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

์ž…๋ ฅ

์ฒซ์งธ ์ค„ : ์ •์ ์˜ ๊ฐœ์ˆ˜ $N$, ๊ฐ„์„ ์˜ ๊ฐœ์ˆ˜ $M$

๋‘˜์งธ ์ค„ ~ $M$๊ฐœ : ๊ฐ„์„ ์˜ ์–‘ ๋ ์  u, v

์ถœ๋ ฅ

์—ฐ๊ฒฐ ์š”์†Œ์˜ ๊ฐœ์ˆ˜

<aside> ๐Ÿ“Ž https://www.acmicpc.net/problem/11724

</aside>

๐Ÿ’ก์•Œ๊ณ ๋ฆฌ์ฆ˜ ์„ค๊ณ„

  1. ์ธ์ ‘๋ฆฌ์ŠคํŠธ๋ฅผ ์ด์šฉํ•˜์—ฌ ๊ทธ๋ž˜ํ”„ ์ดˆ๊ธฐํ™”
  2. dfs ์‚ฌ์šฉํ•˜์—ฌ ํƒ์ƒ‰ (start_node = 1
    1. node์™€ ์ธ์ ‘ํ•œ ๋…ธ๋“œ ๋ฐฉ๋ฌธ
    2. ๋ฐฉ๋ฌธ ์™„๋ฃŒ์‹œ ๋” ์ด์ƒ ๋ฐฉ๋ฌธํ•˜์ง€ ์•Š๋„๋ก ์ด๋ฅผ ํ‘œ๊ธฐํ•  ์ˆ˜ ์žˆ๋Š” ๋ฌด์–ธ๊ฐ€ ์กฐ์น˜ ์ทจํ•˜๊ธฐ

๐Ÿ’ก์ฝ”๋“œ

import sys
from collections import defaultdict

v, e = map(int, sys.stdin.readline().strip().split())
graph = defaultdict(list)

for _ in range(e):
    a, b = map(int, sys.stdin.readline().strip().split())
    graph[a].append(b)
    graph[b].append(a)

def dfs(node):
    if node not in visited:
        visited.add(node)
        for next in graph[node]:
            dfs(next)
        return 1
    return 0

visited = set()
cnt = 0
for idx in range(v):
    cnt += dfs(idx + 1)

print(cnt)

๐Ÿ’ก์‹œ๊ฐ„๋ณต์žก๋„

๊ทธ๋ž˜ํ”„ ์ดˆ๊ธฐํ™” $O(e)$

๋ชจ๋“  ๋…ธ๋“œ ๋ฐฉ๋ฌธ(dfs) $O(v + e)$