Clear and Present Danger
InterviewTime limit1sMemory limit128 MB
Given a danger matrix and a required sequence of islands, find the minimum total danger of a walk that visits those islands in order, allowing detours through others.
- Level
Medium4 of 10
- Topics
- Graph, Shortest path, Dynamic programming, Greedy
- Solved
- No attempts yet
Problem
Farmer John is sailing in search of legendary treasure hidden on one of islands, conveniently numbered through ().
The treasure map tells him that, before the treasure will appear, he must travel through a sequence of islands () in the given order. The route starts at island and ends at island (that is, and ). He may stop at other islands along the way and may visit the same island more than once, but he must visit in exactly this order.
Farmer John wants to avoid pirates and knows the pirate-danger rating () between every pair of islands. The total danger of a route is the sum of the danger ratings of every segment he travels.
Help Farmer John find the least dangerous route that satisfies the treasure map's requirement, and report its total danger.
Input
- Line 1: Two space-separated integers and .
- Next lines: line contains a single integer , the -th island Farmer John must visit (, ).
- Next lines: line contains integers; the -th integer is the danger rating of the path between island and island . The -th integer on line is always .
Output
- A single integer: the minimum total danger Farmer John must encounter to obtain the treasure.
Hint
You do not have to travel directly between two consecutive required islands — routing through other islands can be safer. For example, going directly between island and island has danger , but the route costs only . Using the safest path between each consecutive required pair (, , ) gives a total danger of .