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
/
Copy path4.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))