๊ธ€ ์ž‘์„ฑ์ž: ์ด์ง€์›๐ŸŒฉ๏ธ
 

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

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

www.acmicpc.net

๋ฌธ์ œ

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

 

๋‚ด๊ฐ€ ์ž‘์„ฑํ•œ ์ฝ”๋“œ

# https://www.acmicpc.net/problem/11724
# ์—ฐ๊ฒฐ ์š”์†Œ์˜ ๊ฐœ์ˆ˜ 
import sys 
def bfs(start_v): 
	discovered = [start_v] 
    queue = [start_v] 
    while queue:
    x = queue.pop(0)
    if x in graph:
    	for w in graph[x]:
        	if w not in discovered:
            	discovered.append(w)
                queue.append(w)
	return discovered

n, m = map(int, sys.stdin.readline().split()) 
graph = dict() 
for _ in range(m): 
	u, v = map(int, sys.stdin.readline().split()) 
    if u in graph: 
    	graph[u].append(v) 
    else: 
    	graph[u] = [v]
	if v in graph:
    	graph[v].append(u)
	else: 
    	graph[v] = [u] 

total = 0 
visited = [] 
for i in range(1, n+1): 
	if i not in visited: 
    	visited.extend(bfs(i)) 
        total += 1 
print(n - len(visited) + total)

 

ํ’€์ด

n, m = map(int, sys.stdin.readline().split()) 
graph = dict() 
for _ in range(m): 
	u, v = map(int, sys.stdin.readline().split()) 
    if u in graph:
    	graph[u].append(v) 
    else: 
    	graph[u] = [v] 
	if v in graph: 
    	graph[v].append(u) 
	else: 
    	graph[v] = [u]

์ด ๋ฌธ์ œ๋ฅผ ํ’€๋ฉด์„œ ๋ฌธ์ œ๋ฅผ ๊ผผ๊ผผํžˆ ์ฝ์–ด์•ผ ํ•œ๋‹ค๋Š” ๊ฑธ ๋Š๊ผˆ๋‹ค. ์ง€๋ฌธ์—๋Š” ์ƒ๊ฐ๋ณด๋‹ค ๋งŽ์€ ํžŒํŠธ๊ฐ€ ์žˆ๋‹ค. ๊ฐ™์€ ๊ฐ„์„ ์€ ํ•œ ๋ฒˆ๋งŒ ์ฃผ์–ด์ง„๋‹ค๊ณ  ์“ฐ์—ฌ์ ธ ์žˆ์–ด์„œ ๋”•์…”๋„ˆ๋ฆฌ์— ์ €์žฅํ•ด์ค„ ๋•Œ key๊ฐ€ u์ผ ๋•Œ, key๊ฐ€ v์ผ ๋•Œ ๋‘˜ ๋‹ค ์ €์žฅํ•ด์คฌ๋‹ค.

total = 0
visited = [] 
for i in range(1, n+1): 
	if i not in visited: 
	visited.extend(bfs(i)) 
    total += 1 
print(n - len(visited) + total)

๊ทธ ๋‹ค์Œ์—๋Š” ์ผ๋ฐ˜์ ์ธ ๋Š๋‚Œ์œผ๋กœ.. ๊ทธ๋ž˜ํ”„๋ฅผ ์ˆœํšŒํ•˜๋ฉด์„œ ๋ฐฉ๋ฌธํ•œ ๋ฐฐ์—ด์— ์—†์œผ๋ฉด bfs ํ•จ์ˆ˜๋ฅผ ํ†ตํ•ด ํƒ์ƒ‰ํ•˜๊ณ , ํƒ์ƒ‰ํ•œ discovered ๋ฐฐ์—ด์„ visited ๋ฐฐ์—ด์— ์ถ”๊ฐ€ํ•œ๋‹ค. ๋งˆ์ง€๋ง‰ ์ถœ๋ ฅ๋ฌธ์ด ํ•ต์‹ฌ์ธ๋ฐ, ์ด ๊ธ€์˜ ๋‹ต๋ณ€์„ ํ†ตํ•ด ์•Œ์•˜๋‹ค. ์ด์–ด์ง€๋Š” ๊ฐ„์„ ์ด ์—†๋‹ค๊ณ  ์ •์ ์ด ์—†๋Š”๊ฒŒ ์•„๋‹ˆ๋‹ค. ์ „์ฒด ์ •์ ์˜ ๊ฐœ์ˆ˜์—์„œ ๋ฐฉ๋ฌธํ•œ ์š”์†Œ์˜ ๊ฐœ์ˆ˜๋ฅผ ๋นผ๊ณ , total์— ์ €์žฅํ•ด๋‘” ์ด์–ด์ง„ ์„ ์˜ ๊ฐœ์ˆ˜๋ฅผ ๋”ํ•ด์„œ ์ถœ๋ ฅํ–ˆ๋‹ค.

๋ฐ˜์‘ํ˜•