다익스트라 알고리즘

#그래프 이론 #다익스트라

백준 10282번 : 해킹

- 그래프 이론, 다익스트라

1. 풀이

import heapq

def dijkstra(start):
  heap_data = []
  heapq.heappush(heap_data, (0, start))
  distance[start] = 0
  while heap_data:
    dist, now = heapq.heappop(heap_data)
    if distance[now] < dist:
     continue
    for i in adj[now]:
      cost = dist + i[1]
      if distance[i[0]] > cost:
        distance[i[0]] = cost
        heapq.heappush(heap_data, (cost, i[0]))

# 테스트 케이스 수만큼 반복
for _ in range(int(input())):
  # n: 컴퓨터 개수
  # m: 의존성 개수 
  # start: 해킹당한 컴퓨터의 번호 
  n, m, start = map(int, input().split())
  adj = [[] for i in range(n + 1)]
  distance = [float('inf')] * (n + 1)
  for _ in range(m):
    # 컴퓨터 x가 컴퓨터 y를 의존하며, 컴퓨터 y가 감염되면 cost초 후 컴퓨터 x도 감염됨을 뜻한다.
    x, y, cost = map(int, input().split())
    # 2차원 배열 내부에 튜플 존재
    adj[y].append((x, cost))

  dijkstra(start)

  count = 0
  max_distance = 0

  for i in distance:
    if i != float('inf'):
      count += 1
      if i > max_distance:
        max_distance = i
  print(count, max_distance)

백준 5719번 : 거의 최단 경로

- 그래프 이론, 그래프 탐색, 다익스트라

1. 시간 초과 풀이

테스트 케이스는 맞으나 시간 초과가 발생한다. 문제 풀이 방식에 역추적이 들어있으니 충분히 고민해 볼 문제다.


백준 4485번 : 녹색 옷 입은 애가 젤다지?

- 그래프 이론, 다익스트라

1. 풀이

백준 1987번 알파벳 - 백트래킹과 유사한 문제다. 두 문제 비교해볼 것.


백준 11779번 : 최소비용 구하기2

- 그래프 이론, 다익스트라

1. 풀이

테스트 케이스 출력값이

로 나온다. 1 3 5나 1 4 5는 똑같이 최단 거리가 4이고 3개의 노드를 지나는 것이 동일하므로 문제는 없다고 생각한다. (1 3 5가 나와야 할 조건도 없음)


백준 1854번 : K번째 최단경로 찾기

- 그래프 이론, 다익스트라

1. 풀이

테스트 케이스는 통과했으나 정답은 아니다.

Last updated