Under construction

Still being built. Things may change

Cow Routing II

Interview

Time limit1sMemory limit256 MB

Summary
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 NN 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 AA, where her farm is, to city BB, 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 AA, BB, and NN, separated by spaces. (1≤A≤100001 \le A \le 10000, 1≤B≤100001 \le B \le 10000, 1≤N≤5001 \le N \le 500)

The next 2N2N 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 11 and 10001000, and the number of cities is an integer between 11 and 500500. The second line lists the cities on the route in flight order, each given as an integer between 11 and 1000010000.

Output

Print, on one line, the minimum fare to travel from city AA to city BB using at most two routes. If no such itinerary exists, print −1-1. If AA equals BB, print 00.

Examples5

  1. Example 1

    Input
    1 2 3
    3 3
    3 2 1
    4 4
    2 1 4 3
    8 5
    4 1 7 8 2
    
    Expected output
    7
    
  2. Example 2

    Input
    1 5 1
    10 5
    1 2 3 4 5
    
    Expected output
    10
    
  3. Example 3

    Input
    1 2 1
    5 2
    2 1
    
    Expected output
    -1
    
  4. Example 4

    Input
    4 4 2
    3 3
    1 4 9
    2 2
    9 4
    
    Expected output
    0
    
  5. Example 5

    Input
    1 4 4
    1 2
    1 2
    1 2
    2 3
    1 2
    3 4
    5 2
    1 4
    
    Expected output
    5