Road to the Olympiad
Time limit2sMemory limit1024 MB
Given a graph where flights are added and removed, find the cheapest route between two cities using at most two flights.
- Level
Hard8 of 10
- Topics
- Graph, Hash map, Shortest path
- Solved
- No attempts yet
Statement
Miша solved every problem in the qualifying round and received an invitation to the on-site stage of a closed informatics olympiad. He plans to fly to the venue and wants to make at most one transfer, so he uses at most two flights. Among all such options, he wants the cheapest one.
The jury keeps the venue and date of the on-site stage secret, so Miша cannot know in advance which city he will start from. New regular flights are added from time to time, and some old ones are removed from the schedule. Write a program that answers the following queries:
- Add a new regular flight.
- Remove a flight.
- Find the minimum cost of a route between two cities, considering only routes with no transfers and routes with one transfer.
Each flight connects a pair of cities and and has cost . All flights are two-way, so they can be used in both directions.
Input
The first line contains two integers and (, ), the number of cities and the number of flights available at the start.
Each of the next lines contains three integers , , and (, , ), the cities connected by the -th flight and its cost.
The next line contains one integer (), the number of queries.
Each of the next lines describes a query in one of three formats:
- (, , ) adds a regular flight between cities and with cost .
- (, ) removes the regular flight between cities and . It is guaranteed that such a flight exists at the time of the query.
- (, ) asks for the cheapest way to travel from city to city , using at most one transfer.
At any moment, there is at most one regular flight between any pair of cities. There is at least one query of the third type.
Output
For each query of the third type, print the minimum cost of a trip using at most one transfer. If no suitable route exists between the given pair of cities, print .
Hint
For the sample queries of the third type, the optimal routes in input order are:
- Through city 2. A direct flight exists, but it is not the cheapest route.
- Through city 3.
- Through city 2.
- Through city 3.
- No suitable route exists.
- The direct flight.
- Through city 1.
- Through city 4.
- No suitable route exists.