Sea Journey
InterviewTime limit1sMemory limit128 MB
Process a stream of queries where each query asks for the shortest path between two islands after a sequence of edge insertions.
- Level
Medium6 of 10
- Topics
- Shortest path, Graph, Dynamic programming, Simulation
- Solved
- No attempts yet
Problem
The country of JOI has islands, numbered from to . A network of boat routes connecting the islands is being developed.
You work at a ticket office that handles boat tickets. Many people in JOI want to travel between islands as cheaply as possible by boat, and they send you order forms listing a departure island and a destination island.
Your job is: as soon as you receive an order form, compute the cheapest possible fare among all ways of traveling from the departure to the destination by transferring between boats, and report it to the customer.
Depending on the route, however, it may be impossible to travel by boat at all. In that case you must answer , meaning the trip is impossible. In addition, new boat routes between islands keep starting service in JOI, and you are told about them as they appear. Every answer you give must reflect the most up-to-date information.
Given the customers' order forms and the information about newly started boat routes as input, write a program that produces the answer for each order form.
Input
The first line contains two integers and (, ): there are islands, followed by command lines.
Each of the next lines contains either or integers separated by spaces.
- If the first number is , the line is a customer order form.
- The line contains three integers , , (, , ).
- It means a customer sent an order form with departure island and destination island .
- If the first number is , the line describes a boat route that has just started service.
- The line contains four integers , , , (, , , ).
- A boat running back and forth between islands and has started service; the fare from to and the fare from to are both .
- This boat must be taken into account for all order forms after this line.
Initially no boats are in service. At most of the input lines describe boat routes. Note that several different boats may operate between the same pair of islands.
Output
Let be the number of order-form lines in the input.
Print lines. Line () contains an integer: the answer to the -th order form.
That is, if it is possible to travel from the departure to the destination of the -th order form by transferring between boats, print the minimum total fare; if it is impossible, print .
Explanation
The figure below illustrates, for the first input, how the boat routes start service one by one and the answer given for each order form.
