One step of distance-vector routing: a router adds each link cost to what that neighbour says its own cost is, and takes the smallest.
What to build
A program that picks the best neighbour for one destination.
Requirements
- For every neighbour, add the link cost and the neighbour's advertised cost to the destination.
- Print
cost C via K, where C is the smallest total and K is the number of the neighbour (counting from 1; the first one on a tie). - If no neighbour can reach the destination (all advertised costs are
inf), printunreachable.
Input
A line with n neighbours, then n lines link_cost advertised_cost. The advertised cost may be the word inf.
Output
cost C via K or unreachable.
Constraints
1 ≤ n ≤ 20; costs are whole numbers from 0 to 1000.
Example
Input:
2
4 1
2 1
Output:
cost 3 via 2
Why it works
A path through a neighbour costs the link to it plus what that neighbour pays to go on, so the best path is the smallest such sum. This is the Bellman-Ford rule in one step.
Examples
2 4 1 2 1
cost 3 via 2
3 1 inf 2 inf 3 inf
unreachable
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
For each neighbour, the total is link cost plus the neighbour's cost to the destination. Use float("inf") when the cost is inf.
Hint 2
Keep the smallest total and its position (counting from 1). The first neighbour wins a tie.
Hint 3
If every total is infinite, print unreachable.
Solution
Show one correct solution (try it yourself first)
n = int(input())
best, via = None, 0
for i in range(1, n + 1):
link, adv = input().split()
if adv == "inf":
continue
total = int(link) + int(adv)
if best is None or total < best:
best, via = total, i
if best is None:
print("unreachable")
else:
print("cost", best, "via", via)
▶ Open this solution in the compiler, then press Visualize to watch it run step by step
Lesson: Routing algorithms: link state and distance vector →