답이 맞긴한데 시간초과..
시간초과
import sys
from collections import deque
T = int(sys.stdin.readline())
def infection(graph, c, n):
time = [sys.maxsize]*(n+1)
time[c]=0
q = deque()
q.append(c)
while q:
p = q.popleft()
for i, w in graph[p]:
time[i] = min(time[i], time[p]+w)
if i not in q:
q.append(i)
cnt = 0
ans = 0
for t in time:
if t != sys.maxsize:
cnt+=1
ans = max(ans, t)
print(cnt, ans)
for _ in range(T):
n, d, c = map(int, sys.stdin.readline().split())
graph = {i:[] for i in range(n+1)}
for _ in range(d):
a, b, s = map(int, sys.stdin.readline().split())
graph[b].append([a,s])
infection(graph, c, n)
힙을 이용해 성공
import sys
import heapq
def dijkstra(graph, c, n):
distances = [sys.maxsize]*(n+1)
heap = [[0, c]]
distances[c]=0
while heap:
current_distance, current_idx = heapq.heappop(heap)
for next_idx, next_distance in graph[current_idx]:
distance = current_distance + next_distance
if distances[next_idx]>distance:
distances[next_idx]=distance
heapq.heappush(heap, [distance, next_idx])
cnt = 0
ans = 0
for d in distances:
if d != sys.maxsize:
cnt+=1
ans = max(ans, d)
print(cnt, ans)
T = int(sys.stdin.readline())
for _ in range(T):
n, d, c = map(int, sys.stdin.readline().split())
graph = {i:[] for i in range(n+1)}
for _ in range(d):
a, b, s = map(int, sys.stdin.readline().split())
graph[b].append([a,s])
dijkstra(graph, c, n)
다익스트라를 구현하는 방법
- 우선순위 큐
- 리스트
- O(n**2)
[알고리즘] 다익스트라 최단경로 with Python
💡 최단 경로 알고리즘 가장 짧은 경로를 찾는 알고리즘이다. 그래서 '길찾기'문제라고도 불린다. 학부 수준에서 사용하는 최단 거리 알고리즘은 다익스트라 최단 경로 알고리즘, 플로이드 워
doing7.tistory.com
'알고리즘' 카테고리의 다른 글
[누적합] 백준 3020 개똥벌레 (0) | 2022.03.20 |
---|---|
[dijkstra] 백준 11779 최소비용 구하기2(다익스트라 + 경로 노드) (0) | 2022.03.19 |
[그래프] 백준 1261 알고스팟 (0) | 2022.03.16 |
[그래프] 백준 1197 최소 스패닝 트리(kruskal/prim) (0) | 2022.03.14 |
[그래프] 백준 2206 벽 부수고 이동하기 (0) | 2022.03.13 |
댓글