Part Acquisition
InterviewTime limit1sMemory limit1024 MB
Given N one-way barter offers between K item types, find the fewest trades that turn item 1 into item K and list the trade order.
- Level
Easy3 of 10
- Topics
- BFS, Graph, Shortest path
- Solved
- No attempts yet
Problem
The cows have been sent on a mission through space to acquire a new milking machine for their barn. They are flying through a cluster of stars containing N (1 ≤ N ≤ 50,000) planets, each with a trading post.
The cows have determined which of K (1 ≤ K ≤ 1,000) types of objects (numbered 1..K) each planet in the cluster desires, and which products they have to trade. No planet has developed currency, so they work under the barter system: all trades consist of each party trading exactly one object (presumably of different types).
The cows start from Earth with a canister of high quality hay (item 1), and they desire a new milking machine (item K). Help them find the best way to make a series of trades at the planets in the cluster to get item K. If this task is impossible, output -1.
Input
Line 1 contains two space-separated integers, N and K.
Line i+1 (for 1 ≤ i ≤ N) contains two space-separated integers, a_i and b_i. Planet i gives item b_i in order to receive item a_i.
Output
Line 1: One more than the minimum number of trades needed to get item K, or -1 if the cows cannot obtain item K.
Lines 2 to T+1: The ordered list of the objects the cows possess, in the sequence of trades.
Hint
The cows possess 4 objects in total. First they trade object 1 for object 3, then object 3 for object 2, then object 2 for object 5.