๋งž์™œํ‹€

[python] ๋ฐฑ์ค€ - 1325. ํšจ์œจ์ ์ธ ํ•ดํ‚น ๋ณธ๋ฌธ

Algorithm Problem/Python

[python] ๋ฐฑ์ค€ - 1325. ํšจ์œจ์ ์ธ ํ•ดํ‚น

deo2kim 2020. 10. 28. 09:59
๋ฐ˜์‘ํ˜•

๐Ÿค”๋ฌธ์ œ ํ•ด๊ฒฐ

  • S2 | ๊ทธ๋ž˜ํ”„, BFS(DFS)

๋‹จ์ˆœํ•œ ๊ทธ๋ž˜ํ”„ ๋ฌธ์ œ์˜€๋Š”๋ฐ ์ „๋ถ€๋‹ค ์‹œ๊ฐ„์ดˆ๊ณผ ๋ฐœ์ƒ....

๋‹ค๋ฅธ ๋ถ„๋“ค ์ œ์ถœํ•œ๊ฒƒ๋„ ๋ณด๋‹ˆ๊นŒ ๋Œ€๋ถ€๋ถ„ ์‹œ๊ฐ„์ดˆ๊ณผ์ด๋‹ค. (๊ทธ๋ž˜์„œ pypy3๋กœ ์ œ์ถœํ•˜๋‹ˆ ์„ฑ๊ณต)

 

ํ’€์ด๋ฐฉ๋ฒ•์€

  1. ์ธ์ ‘๋ฆฌ์ŠคํŠธ ์ƒ์„ฑ (์ด ๋ฌธ์ œ์—์„œ๋Š” a->b๊ฐ€ ์•„๋‹ˆ๋ผ b->a ์ด๋‹ค)
  2. ๋ชจ๋“  ๋…ธ๋“œ์— ๋Œ€ํ•ด์„œ
  3. BFS๋ฅผ ๋Œ๋ฆฐ๋‹ค. ๊ทธ ๋•Œ ๋ช‡๊ฐœ์˜ ๋…ธ๋“œ๋ฅผ ๋Œ์•˜๋Š”์ง€ ์ˆซ์ž๋ฅผ ์„ธ์ค€๋‹ค.
  4. ๊ฐ€์žฅ ๋†’์€ ์นด์šดํŠธ์˜ ๋…ธ๋“œ๋“ค์„ ์ถœ๋ ฅํ•œ๋‹ค.

๋‹ค๋ฅธ ๋ถ„๋“ค์˜ ํ’€์ด๋ฅผ ๋ดค๋Š”๋ฐ ํ’€์ด๊ฐ€ ๋‚˜๋ž‘๋˜‘๊ฐ™๋‹ค. ํ•˜์ง€๋งŒ ์–ด๋–ป๊ฒŒ ํ†ต๊ณผํ–ˆ๋Š”์ง€...

 

๐Ÿ’ป์†Œ์Šค ์ฝ”๋“œ

import sys
from collections import defaultdict
from collections import deque


def bfs(start):
    q = deque([start])
    visited = [0] * (N + 1)
    visited[start] = 1
    cnt = 0
    while q:
        c = q.popleft()
        cnt += 1
        for nei in adj[c]:
            if not visited[nei]:
                q.append(nei)
                visited[nei] = 1

    return cnt


input = sys.stdin.readline

N, M = map(int, input().split())

adj = defaultdict(list)
for _ in range(M):
    e, s = map(int, input().split())
    adj[s].append(e)

print(adj)

result = []
for i in range(1, N + 1):
    result.append([bfs(i), i])

print(result)

result.sort(key=lambda x: (-x[0], x[1]))

max_cnt = result[0][0]
for r in result:
    if r[0] == max_cnt:
        print(r[1], end=" ")
    else:
        break

 

๐Ÿ“•๋ฌธ์ œ ํ™•์ธ

์ถœ์ฒ˜: BACKJOON ONLINE JUDGE

๋งํฌ: https://www.acmicpc.net/problem/1325

 

1325๋ฒˆ: ํšจ์œจ์ ์ธ ํ•ดํ‚น

์ฒซ์งธ ์ค„์—, N๊ณผ M์ด ๋“ค์–ด์˜จ๋‹ค. N์€ 10,000๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™์€ ์ž์—ฐ์ˆ˜, M์€ 100,000๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™์€ ์ž์—ฐ์ˆ˜์ด๋‹ค. ๋‘˜์งธ ์ค„๋ถ€ํ„ฐ M๊ฐœ์˜ ์ค„์— ์‹ ๋ขฐํ•˜๋Š” ๊ด€๊ณ„๊ฐ€ A B์™€ ๊ฐ™์€ ํ˜•์‹์œผ๋กœ ๋“ค์–ด์˜ค๋ฉฐ, "A๊ฐ€ B๋ฅผ ์‹ ๋ขฐํ•œ

www.acmicpc.net

๋ฐ˜์‘ํ˜•