Heat Wave
InterviewTime limit1sMemory limit128 MB
Given an undirected weighted graph, find the minimum total cost of a route from a source town to a destination town.
- Level
Medium4 of 10
- Topics
- Graph, Shortest path, Heap, Greedy
- Solved
- No attempts yet
Problem
Texas is suffering a heat wave this summer. Farmer John is in charge of delivering plenty of ice-cold milk from Wisconsin to Texas so the Texans can beat the heat.
The routes that can carry the milk pass through a total of towns, numbered through (including the starting and ending towns). Each road connects two towns bidirectionally and has a traversal cost (gasoline, tolls, and so on).
Below is an example map of seven towns. Town is the source of the milk and town is its destination; the bracketed integers are the traversal costs.
[1]----1---[3]-
/ \
[3]---6---[4]---3--[3]--4
/ / /|
5 --[3]-- --[2]- |
\ / / |
[5]---7---[2]--2---[3]---
| /
[1]------
For example, traversing costs .
Given all roads (each described by its two endpoints , and cost ), find the smallest total cost to travel from the starting town to the destination town .
Constraints: , , , , .
Input
- Line 1: Four space-separated integers , , , and .
- Lines through : Line describes road with three space-separated integers , , and .
Output
- Line 1: A single integer, the total cost of the shortest route from to . At least one route is guaranteed to exist.
Hint
In the sample input, the shortest route is with cost .