forked from ndb796/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path4.py
More file actions
59 lines (52 loc) ยท 2.14 KB
/
4.py
File metadata and controls
59 lines (52 loc) ยท 2.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import heapq
import sys
input = sys.stdin.readline
INF = int(1e9) # ๋ฌดํ์ ์๋ฏธํ๋ ๊ฐ์ผ๋ก 10์ต์ ์ค์
# ๋
ธ๋์ ๊ฐ์, ๊ฐ์ ์ ๊ฐ์๋ฅผ ์
๋ ฅ๋ฐ๊ธฐ
n, m = map(int, input().split())
# ์์ ๋
ธ๋๋ฅผ 1๋ฒ ํ๊ฐ์ผ๋ก ์ค์
start = 1
# ๊ฐ ๋
ธ๋์ ์ฐ๊ฒฐ๋์ด ์๋ ๋
ธ๋์ ๋ํ ์ ๋ณด๋ฅผ ๋ด๋ ๋ฆฌ์คํธ๋ฅผ ๋ง๋ค๊ธฐ
graph = [[] for i in range(n + 1)]
# ์ต๋จ ๊ฑฐ๋ฆฌ ํ
์ด๋ธ์ ๋ชจ๋ ๋ฌดํ์ผ๋ก ์ด๊ธฐํ
distance = [INF] * (n + 1)
# ๋ชจ๋ ๊ฐ์ ์ ๋ณด๋ฅผ ์
๋ ฅ๋ฐ๊ธฐ
for _ in range(m):
a, b = map(int, input().split())
# a๋ฒ ๋
ธ๋์ b๋ฒ ๋
ธ๋์ ์ด๋ ๋น์ฉ์ด 1์ด๋ผ๋ ์๋ฏธ(์๋ฐฉํฅ)
graph[a].append((b, 1))
graph[b].append((a, 1))
def dijkstra(start):
q = []
# ์์ ๋
ธ๋๋ก ๊ฐ๊ธฐ ์ํ ์ต๋จ ๊ฒฝ๋ก๋ 0์ผ๋ก ์ค์ ํ์ฌ, ํ์ ์ฝ์
heapq.heappush(q, (0, start))
distance[start] = 0
while q: # ํ๊ฐ ๋น์ด์์ง ์๋ค๋ฉด
# ๊ฐ์ฅ ์ต๋จ ๊ฑฐ๋ฆฌ๊ฐ ์งง์ ๋
ธ๋์ ๋ํ ์ ๋ณด๋ฅผ ๊บผ๋ด๊ธฐ
dist, now = heapq.heappop(q)
# ํ์ฌ ๋
ธ๋๊ฐ ์ด๋ฏธ ์ฒ๋ฆฌ๋ ์ ์ด ์๋ ๋
ธ๋๋ผ๋ฉด ๋ฌด์
if distance[now] < dist:
continue
# ํ์ฌ ๋
ธ๋์ ์ฐ๊ฒฐ๋ ๋ค๋ฅธ ์ธ์ ํ ๋
ธ๋๋ค์ ํ์ธ
for i in graph[now]:
cost = dist + i[1]
# ํ์ฌ ๋
ธ๋๋ฅผ ๊ฑฐ์ณ์, ๋ค๋ฅธ ๋
ธ๋๋ก ์ด๋ํ๋ ๊ฑฐ๋ฆฌ๊ฐ ๋ ์งง์ ๊ฒฝ์ฐ
if cost < distance[i[0]]:
distance[i[0]] = cost
heapq.heappush(q, (cost, i[0]))
# ๋ค์ต์คํธ๋ผ ์๊ณ ๋ฆฌ์ฆ์ ์ํ
dijkstra(start)
# ๊ฐ์ฅ ์ต๋จ ๊ฑฐ๋ฆฌ๊ฐ ๋จผ ๋
ธ๋ ๋ฒํธ(๋๋น์ด๊ฐ ์จ์ ํ๊ฐ์ ๋ฒํธ)
max_node = 0
# ๋๋ฌํ ์ ์๋ ๋
ธ๋ ์ค์์, ๊ฐ์ฅ ์ต๋จ ๊ฑฐ๋ฆฌ๊ฐ ๋จผ ๋
ธ๋์์ ์ต๋จ ๊ฑฐ๋ฆฌ
max_distance = 0
# ๊ฐ์ฅ ์ต๋จ ๊ฑฐ๋ฆฌ๊ฐ ๋จผ ๋
ธ๋์์ ์ต๋จ ๊ฑฐ๋ฆฌ์ ๋์ผํ ์ต๋จ ๊ฑฐ๋ฆฌ๋ฅผ ๊ฐ์ง๋ ๋
ธ๋๋ค์ ๋ฆฌ์คํธ
result = []
for i in range(1, n + 1):
if max_distance < distance[i]:
max_node = i
max_distance = distance[i]
result = [max_node]
elif max_distance == distance[i]:
result.append(i)
print(max_node, max_distance, len(result))