๋ฐ์ํ
๐ค๋ฌธ์ ํด๊ฒฐ
-
S2 | ๊ทธ๋ํ, BFS(DFS)
๋จ์ํ ๊ทธ๋ํ ๋ฌธ์ ์๋๋ฐ ์ ๋ถ๋ค ์๊ฐ์ด๊ณผ ๋ฐ์....
๋ค๋ฅธ ๋ถ๋ค ์ ์ถํ๊ฒ๋ ๋ณด๋๊น ๋๋ถ๋ถ ์๊ฐ์ด๊ณผ์ด๋ค. (๊ทธ๋์ pypy3๋ก ์ ์ถํ๋ ์ฑ๊ณต)
ํ์ด๋ฐฉ๋ฒ์
- ์ธ์ ๋ฆฌ์คํธ ์์ฑ (์ด ๋ฌธ์ ์์๋ a->b๊ฐ ์๋๋ผ b->a ์ด๋ค)
- ๋ชจ๋ ๋ ธ๋์ ๋ํด์
- BFS๋ฅผ ๋๋ฆฐ๋ค. ๊ทธ ๋ ๋ช๊ฐ์ ๋ ธ๋๋ฅผ ๋์๋์ง ์ซ์๋ฅผ ์ธ์ค๋ค.
- ๊ฐ์ฅ ๋์ ์นด์ดํธ์ ๋ ธ๋๋ค์ ์ถ๋ ฅํ๋ค.
๋ค๋ฅธ ๋ถ๋ค์ ํ์ด๋ฅผ ๋ดค๋๋ฐ ํ์ด๊ฐ ๋๋๋๊ฐ๋ค. ํ์ง๋ง ์ด๋ป๊ฒ ํต๊ณผํ๋์ง...
๐ป์์ค ์ฝ๋
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
๋ฐ์ํ
'Algorithm Problem > Python' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[python] ๋ฐฑ์ค - 14719. ๋น๋ฌผ (0) | 2020.10.30 |
---|---|
[python] ๋ฐฑ์ค - 12865. ํ๋ฒํ ๋ฐฐ๋ญ (0) | 2020.10.29 |
[python] ๋ฐฑ์ค - 10773. ๊ดํธ (0) | 2020.10.27 |
[python] ๋ฐฑ์ค - 2512. ์์ฐ (0) | 2020.10.26 |
[python] ๋ฐฑ์ค - 1874. ์คํ ์์ด (0) | 2020.10.25 |