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.
Medium7GraphGreedyHash mapNo attempts yetTime limit5sMemory limit512 MBIvan is planning a large European tour with his jazz band. There are n cities in Europe, numbered with integers 1 through n. Ivan is planning d concerts in cities a1,a2,…,ad in that exact order. Two consecutive concerts are never in the same city (ai=ai+1), some cities may be visited many times, and the tour ends in the same city where it began (a1=ad).
Ivan always takes a direct flight between cities ai and ai+1. 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:
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 ai to ai+1 for every i=1,2,…,d−1. You may assume that the journey can be completed using the given airfares.
The first line contains two integers n and d (2≤n,d≤300000): the number of cities in Europe and the number of concerts.
The second line contains the integers a1,a2,…,ad (1≤ai≤n, ai=ai+1, a1=ad): the planned tour schedule.
The third line contains an integer m (3≤m≤300000): the number of airfares. The k-th of the following m lines contains four tokens sk, dk, tk, pk that describe the k-th airfare:
O or R, denoting a one-way or a round trip ticket, respectively.Output the least amount of money needed to purchase tickets that allow Ivan to complete the planned tour.