Jazz Journey
Time limit5sMemory limit512 MB
Given a fixed closed tour and ticket prices for one-way and round-trip fares, find the minimum cost to cover every leg of the tour.
Problem
Ivan is planning a large European tour with his jazz band. There are cities in Europe, numbered with integers through . Ivan is planning concerts in cities in that exact order. Two consecutive concerts are never in the same city (), some cities may be visited many times, and the tour ends in the same city where it began ().
Ivan always takes a direct flight between cities and . However, he wants to be smart with his ticket purchases to save money. Airlines price tickets based on supply and demand, so it may happen, for example, that one-way tickets are more expensive than round trip tickets between the same cities.
There are two kinds of tickets available for purchase:
- A one-way ticket from origin city to destination city can be used to fly from to once. It cannot be used in the opposite direction.
- A round trip ticket from origin city to destination city can be used to fly once from to and once from to . The return segment (from to ) does not need to be used. However, the segments have to be flown in order: Ivan may not use the return segment of a ticket to fly from to unless he has already used the first segment of that ticket to fly from to .
You are given a list of available airfares. Find the least amount of money Ivan needs to spend on tickets to complete his journey. Ivan can purchase any number of tickets for each airfare. Once again, Ivan needs to take a direct flight from to for every . You may assume that the journey can be completed using the given airfares.
Input
The first line contains two integers and (): the number of cities in Europe and the number of concerts.
The second line contains the integers (, , ): the planned tour schedule.
The third line contains an integer (): the number of airfares. The -th of the following lines contains four tokens , , , that describe the -th airfare:
- and (, ) are the origin and the destination city, respectively.
- is an uppercase letter
OorR, denoting a one-way or a round trip ticket, respectively. - () is the ticket price, an integer.
Output
Output the least amount of money needed to purchase tickets that allow Ivan to complete the planned tour.