Cow Jogging
InterviewTime limit1sMemory limit128 MB
Given a DAG with edges pointing from higher to lower numbered nodes, report the K shortest path lengths from node N to node 1, with duplicates allowed.
- Level
Medium7 of 10
- Topics
- Graph, Dynamic programming, Shortest path, Heap
- Solved
- No attempts yet
Problem
Bessie has taken heed of the evils of sloth and decided to get fit by jogging from the barn to the pond several times a week. To avoid working too hard, she only jogs downhill to the pond and then ambles back to the barn at her leisure.
The pastures are numbered through (). Whenever , the cow path from pasture to pasture runs downhill. Pasture is the barn at the top of the hill, and pasture is the pond at the bottom.
Tired of always taking the same route, Bessie wants variety: she would like to know the lengths of the shortest routes from the barn to the pond (). Two routes are considered different if they consist of a different sequence of cow paths.
You are given downhill cow paths (). Cow path goes from pasture to pasture () and has length ().
Input
- Line 1: three space-separated integers , , and .
- Lines 2 through : each line describes one downhill cow path with three space-separated integers , , and .
Output
- Print lines. Line contains the length of the -th shortest route, or if no such route exists. If a shortest-route length occurs multiple times, print it that many times.
Hint
For the graph with , the routes from the barn (pasture ) to the pond (pasture ) are , , , , , and , with lengths respectively.