Cow Routing II
InterviewTime limit1sMemory limit256 MB
Find the cheapest fare from city A to city B using at most two ordered flight routes, paying each used route full fare.
- Level
Medium5 of 10
- Topics
- Brute force, Hash map
- Solved
- No attempts yet
Problem
Bessie the cow is tired of the cold winter weather on her farm and plans to fly somewhere warmer for vacation. Only one airline, Air Bovinia, sells tickets to cows, and its tickets have an unusual structure.
Air Bovinia operates planes. Each plane flies one route that visits several cities in a fixed order. For example, one plane might fly a route that starts at city 1, then goes to city 5, then to city 2, and finally to city 8. No city appears twice in the same route.
If Bessie uses a route, she may board at any city on that route and disembark at any city that comes later on the same route. She does not have to board at the first city or disembark at the last city. Each route has a fare, and using any part of the route costs the full fare no matter how many cities she passes. Bessie may use a route only once, so she cannot use one route and later use a different segment of that same route.
Bessie wants the cheapest way to travel from city , where her farm is, to city , her destination. She does not want a complicated itinerary, so she uses at most two routes. Find the minimum fare she must pay.
Input
The first line contains , , and , separated by spaces. (, , )
The next lines describe the routes, two lines per route. The first line of a route contains the fare for that route and the number of cities on it. The fare is an integer between and , and the number of cities is an integer between and . The second line lists the cities on the route in flight order, each given as an integer between and .
Output
Print, on one line, the minimum fare to travel from city to city using at most two routes. If no such itinerary exists, print . If equals , print .