Problem 270
Cheapest Flights Within K Stops
Medium · 20 pts · Graph, Shortest Path, Dynamic Programming
Problem
There are N cities and M one-way flights, each with a price. Find the cheapest way to travel from city S to city D using at most K stops in between, which means at most K + 1 flights. Print the price, or -1 if no such route exists. A route with more stops may be cheaper, but it is not allowed. A Bellman-Ford variant works well: repeat K + 1 rounds, and in each round relax every flight using the prices from the previous round only, so that each round adds at most one flight.
Input
First line: N and M. Next M lines: a flight u v price. Last line: S, D and K.
Output
Print the cheapest price, or -1.
Constraints
1 <= N <= 100; 0 <= M <= 5000; 1 <= price <= 10000; 0 <= K < N; S != D
Example input
4 5 1 2 100 2 3 100 3 4 100 2 4 600 3 1 100 1 4 1
Example output
700
Explanation
The route 1 → 2 → 3 → 4 costs only 300, but it has 2 stops and K = 1. The route 1 → 2 → 4 has one stop and costs 100 + 600 = 700, which is the cheapest allowed route.