[파이썬] 백준 13911 : 집 구하기 (골드2)
풀이
방향성 생각
- 다익스트라
- 맥도날드 따로, 스타벅스 따로 다익스트라를 돌린다.
전체코드
from collections import defaultdict as dd
import heapq as hq
import sys
input = lambda : sys.stdin.readline().rstrip()
INF = float('inf')
N,M = map(int,input().split())
G = [[] for _ in range(N+1)]
for _ in range(M):
a,b,cost = map(int,input().split())
G[a].append((b,cost))
G[b].append((a,cost))
mac,x = map(int,input().split())
mac_set = set(map(int, input().split()))
star,y = map(int,input().split())
star_set = set(map(int,input().split()))
def di(G,locs):
V = [INF]*(N+1)
heap = []
for loc in locs:
V[loc] = 0
hq.heappush(heap,(0,loc))
while heap:
t,x = hq.heappop(heap)
if t > V[x]:
continue
for nx,cost in G[x]:
nt = t + cost
if nt < V[nx]:
V[nx] = nt
hq.heappush(heap,(nt,nx))
return V
max_dist = di(G,mac_set)
star_dist = di(G,star_set)
house = set(range(1,N+1)) - (mac_set|star_set)
answer = INF
for h in house:
if max_dist[h]<= x and star_dist[h]<=y:
answer = min(answer, max_dist[h] + star_dist[h])
print(answer if answer != INF else -1)
코멘트
- 입력 중복간선 처리한다고, defaultdict이나 중복순회하면 느리게 나온다.
- 그냥 다익스트라에서 if t > V[x]: 이거로 필터링하는게 나은듯
'Algorithm > Graph' 카테고리의 다른 글
[파이썬] 백준 15809 : 전국시대 (골드4) (0) | 2025.01.06 |
---|---|
[파이썬] 백준 1956 : 운동 (골드4) (0) | 2025.01.05 |
[파이썬] 백준 1238 : 파티 (골드3) (0) | 2025.01.04 |
[파이썬] 백준 16398 : 행성 연결 (골드4) (0) | 2025.01.02 |
[파이썬] 백준 1922 : 네트워크연결 (골드4) (0) | 2025.01.01 |
[파이썬] 백준 16952 : 체스판 여행 2 (플레4) (0) | 2024.12.07 |
[파이썬] 백준 16959 : 체스판 여행 1 (플레5) (0) | 2024.12.06 |
댓글