배달
코딩테스트 연습 > Summer,Winter Coding(~2018) > 배달
https://programmers.co.kr/learn/courses/30/lessons/12978
Input value =
int(N): number of nodes
list(road): list(distance between start node and next node)
int(K): limit distance
Process = Using dijkstra
Output value = number of nodes satisfied distance < K
from collections import deque
nodes = dict()
dist = {i:float('inf') if i != 1 else 0 for i in range(1, N+1)}
for v1, v2, d in road:
nodes[v1] = nodes.get(v1, []) + [(v2, d)]
nodes[v2] = nodes.get(v2, []) + [(v1, d)]
que = deque([1])
while que:
cur_node = que.popleft() # 시작 노드 추출
for nxt_node, d in nodes[cur_node]: # 시작노드와 연결된 노드와 거리 확인
if dist[nxt_node] > dist[cur_node] + d: # 시작노드와 연결 노드와의 거리의 합이 연결 노드의 최종 거리보다 작으면
dist[nxt_node] = dist[cur_node] + d # 해당 값을 갱신
que.append(nxt_node) # 다음 노드를 탐색하기 위해 시작 노드 갱신
len([i for i in dist.values() if i <= K])
import heapq
total_distance = {node: float('inf') if node!=1 else 0 for node in range(1,N+1)}
nodes = dict()
for start,destination,distance in road:
nodes[start] = nodes.get(start,[])+[(destination,distance)] # 시작 노드와 도착 노드의 관계
nodes[destination] = nodes.get(destination,[])+[(start,distance)] # 도착 노드와 시작 노드의 관계
queue = []
heapq.heappush(queue, 1)
while queue:
now_node = heapq.heappop(queue) # 시작 노드 추출
for next_node, next_distance in nodes[now_node]: # 시작노드와 연결된 노드와 거리 확인
if total_distance[next_node] > total_distance[now_node]+next_distance: # 시작노드와 연결 노드와의 거리의 합이 연결 노드의 최종 거리보다 작으면
total_distance[next_node] = total_distance[now_node]+next_distance # 해당 값을 갱신
heapq.heappush(queue,next_node) # 다음 노드를 탐색하기 위해 시작 노드 갱신
len([d for d in total_distance.values() if d <= K])
from collections import deque
def solution(N, road, K):
nodes = dict()
dist = {i:float('inf') if i != 1 else 0 for i in range(1, N+1)}
for v1, v2, d in road:
nodes[v1] = nodes.get(v1, []) + [(v2, d)]
nodes[v2] = nodes.get(v2, []) + [(v1, d)]
que = deque([1])
while que:
cur_node = que.popleft()
for nxt_node, d in nodes[cur_node]:
if dist[nxt_node] > dist[cur_node] + d:
dist[nxt_node] = dist[cur_node] + d
que.append(nxt_node)
return len([i for i in dist.values() if i <= K])
# Code test
N = 5
road = [[1,2,1],[2,3,3],[5,2,2],[1,4,2],[5,3,1],[5,4,2]]
K = 3
solution(N,road,K)
import heapq
def solution(N, road, K):
total_distance = {node: float('inf') if node!=1 else 0 for node in range(1,N+1)}
nodes = dict()
for start,destination,distance in road:
nodes[start] = nodes.get(start,[])+[(destination,distance)]
nodes[destination] = nodes.get(destination,[])+[(start,distance)]
queue = []
heapq.heappush(queue, 1)
while queue:
now_node = heapq.heappop(queue)
for next_node, next_distance in nodes[now_node]:
if total_distance[next_node] > total_distance[now_node]+next_distance:
total_distance[next_node] = total_distance[now_node]+next_distance
heapq.heappush(queue,next_node)
return len([d for d in total_distance.values() if d <= K])
# Code test
N = 5
road = [[1,2,1],[2,3,3],[5,2,2],[1,4,2],[5,3,1],[5,4,2]]
K = 3
solution(N,road,K)