Skip to content

Commit 13ad0dc

Browse files
authored
Merge pull request #42 from zaqquum/main
김홍주/ 7월 2주차 / 2개
2 parents 9fc08af + 586c36c commit 13ad0dc

File tree

2 files changed

+98
-0
lines changed

2 files changed

+98
-0
lines changed

Hongjoo/lv2/배달.py

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
"""
2+
시작 = 1
3+
if 시작 ~ # 노드(N개) 까지의 최단 거리 <= K : 배달 가능True
4+
다익스트라
5+
"""
6+
import heapq
7+
INF = 2001
8+
9+
def dikstra(graph, distance, start) :
10+
#2. distance 초기화 : (0,start)로 초기화 / q에 (0,start 넣기)
11+
q= []
12+
distance[start] = 0
13+
heapq.heappush(q,(0,start))
14+
#3. q에서 최단 거리(start -> X) & 방문x 노드 선택
15+
while q :
16+
dist , now = heapq.heappop(q) # A->X
17+
if distance[now] < dist: # 방문 완료
18+
continue
19+
#4. Cost(X->B)계산 + Cost(A->X) < Cost(A->B) => distance 업데이트 + q에 넣기
20+
# graph 인접 간선(i[1]) , dist, 현distance[B]
21+
for i in graph[now]: # i = (b,c)....
22+
cost = dist + i[1]
23+
if cost < distance[i[0]] :
24+
distance[i[0]] = cost
25+
heapq.heappush(q,(cost,i[0]))
26+
return distance
27+
28+
def solution(N, road, K):
29+
# input
30+
graph = [[] for _ in range(N+1)]
31+
distance = [INF]*(N+1) # 최단거리 그래프
32+
33+
#0 그래프 필드 정의 a : [(b,c)...] #양방향
34+
road.sort()
35+
for r in road :
36+
a=r[0] ; b = r[1] ; c= r[2]
37+
graph[a].append([b,c])
38+
graph[b].append([a,c])
39+
40+
# 다익스트라
41+
distance = dikstra(graph ,distance, 1)
42+
43+
# 거리 < K 인 마을 개수
44+
count = 0
45+
for city in range(1, N+1) :
46+
if distance[city] <= K :
47+
count+=1
48+
return count
49+
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
"""
2+
4 4 2 1 # 도시 개수 n , 도로 개수 m , 거리 정보 k , 출발 도시 번호 x
3+
1 2
4+
1 3
5+
2 3
6+
2 4 # 2~m 번 a -> b
7+
다익스트라
8+
"""
9+
import heapq
10+
#0 input
11+
INF = 20000
12+
city_count , road_count , target_km , start =map(int,input().split())
13+
14+
#1. graph 그리기 -> 인접 리스트 방식 , 최단거리 테이블
15+
graph = [[] for i in range(city_count+1) ]
16+
distance = [INF]* (city_count+1)
17+
18+
for _ in range(road_count):
19+
a,b = map(int, input().split())
20+
# a -> b ,b 는 a 에서 갈수 있는 인접한 city
21+
for j in range(len(graph)):
22+
if a == j:
23+
graph[a].append((b,1))
24+
25+
26+
# 다익스트라
27+
#1. 초기 노드 설정 #2. 최단거리 테이블 최기화
28+
q =[]
29+
distance[start]=0
30+
heapq.heappush(q, (0,start))
31+
# 2. 최단 거리(heappop) & 방문 x 노드 선택
32+
while q :
33+
dist , now = heapq.heappop(q)
34+
if distance[now] < dist :
35+
continue
36+
#4, Cost(A->X) + Cost(X->B) < Cost(A->B) : 업데이트 & push
37+
for i in graph[now]:
38+
cost = dist + i[1]
39+
if cost < distance[i[0]] :
40+
distance[i[0]] = cost
41+
heapq.heappush(q,(cost,i[0]))
42+
43+
islenK = False
44+
for i in range(1, city_count+1):
45+
if distance[i] == target_km :
46+
islenK = True
47+
print(i)
48+
if not islenK :
49+
print(-1)

0 commit comments

Comments
 (0)