Spaceships
Time limit10sMemory limit256 MB
Ships add and remove one-way routes over time, and each query asks for the star that minimizes total hops from two given stars, or -1 if none exists.
- Level
Hard9 of 10
- Topics
- Graph, Shortest path, Divide and conquer, Union-find
- Solved
- No attempts yet
Problem
Far away in a galaxy, there are civilized stars numbered 1 through . Each star manages one spaceship. A spaceship is either in use, traveling to some other star, or idle. If the spaceship managed by star is in use and heading to star , it shuttles between stars and many times. When the spaceship goes from star to star , ordinary passengers can ride it from to . When it returns from to , however, ordinary passengers cannot board it, because of fuel issues, cargo loading, and similar reasons. While the spaceship managed by star is idle, it waits at star .
All spaceships are idle now. The schedule of future status changes is already set. Each change is one of the following two kinds.
- An idle spaceship managed by star is set to in use, heading to star . This is done only when ordinary passengers cannot ride that spaceship several times to go from to .
- An in-use spaceship managed by star is set to idle.
Two people planning a trip through this galaxy prepare several questions to decide where to meet. At some moment, one person is at star and the other is at star . Can the two of them meet as ordinary passengers using the spaceships? If they can, which star gives the fewest spaceship uses? In other words, does a star exist such that ordinary passengers can ride spaceships several times to get from to and from to ? If it exists, which star minimizes the sum of the number of spaceship uses needed to go from to and the number needed to go from to ?
Input
The first line contains two integers and separated by a space. is the number of stars, and is the total number of status changes and questions.
The following lines describe the status changes and questions in chronological order. Line contains two or three integers separated by spaces. Let be the first integer. Then one of the following holds.
- If , the line contains , , . The spaceship managed by star is set to in use, heading to star . It is guaranteed that , , , that this spaceship is idle at this moment, and that ordinary passengers cannot ride it several times to go from to at this moment.
- If , the line contains , . The spaceship managed by star is set to idle. It is guaranteed that and that this spaceship is in use at this moment.
- If , the line contains , , . This is a question: at this moment, one person is at star and the other is at star . It is guaranteed that , , .
Output
For each question, in order, print one line. If the two can meet, print the number of the star where they should meet to minimize the number of spaceship uses. If they cannot meet, print -1.