Algorithms/Algorithms

์—ฐ๊ฒฐ์š”์†Œ์˜๊ฐœ์ˆ˜ (๋ฐฑ์ค€ 11724)

ํƒฑ์ ค 2021. 10. 12. 16:55

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

๋ฌธ์ œ

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

์ž…๋ ฅ

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

์ถœ๋ ฅ

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

์˜ˆ์ œ ์ž…๋ ฅ 1

6 5

1 2

2 5

5 1

3 4

4 6

์˜ˆ์ œ ์ถœ๋ ฅ 1

2

https://www.acmicpc.net/problem/11724

 

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


import sys
sys.setrecursionlimit(10 ** 6) # python ์žฌ๊ท€ ์ œํ•œ
read = sys.stdin.readline

n, m = map(int, read().split())
graph = [[0 for i in range(n + 1)] for j in range(n + 1)]

for i in range(m):
    a, b = map(int, read().split())
    graph[a][b] = 1
    graph[b][a] = 1

visited = [0] * (n + 1)
count = 0

def dfs(v, visited):
    visited[v] = 1
    for i in range(n + 1):
        if visited[i] == 0 and graph[v][i] == 1:
            dfs(i, visited)

for i in range(1, n + 1):
    if visited[i] == 0:
        dfs(i, visited)
        count += 1

print(count)

์žฌ๊ท€ ์ œํ•œ ๊ฑธ๋ฆฌ์ง€์•Š๊ฒŒ setrecursionlimit ํ•ด์ฃผ๊ธฐ

 

728x90