Ruby on Rails

5

1 votes
Medium
Problem

Ruby is the Minister of Railways of Code-Land. She has been given a map of the train routes between N stations (S1 S2 S3 ... SN). The map contains information about all the direct routes that exits between a pair of stations, and there exists at most one outgoing route from any station Sj. If a route exists between stations Sj and Sk, then the train can only travel from Sj to Sk.

Ruby has decided to improve the railway channel and accepts Q queries based on administrative evaluation.

  • Query 1 X is to remove the railway link originating from station X if exist and make it terminal.
  • Query 2 X is to report the terminal station that can be reached if starting at station X.

INPUT FORMAT :

  • The first line contains the integer N.
  • The second line contains N space separated integers A1 A2 A3.... AN. The ith integer Ai represent that there exist a direct link from station Si to station Ai  and so on. If Ai = -1 then it signifies that no outgoing link exists from station Si  i.e station Sis terminal.
  • The third line contains the single integer Q.
  • The following Q lines contain the query of form 1 X or 2 X

OUTPUT FORMAT :

  • For each query of the form 2 X, print the terminal (last) station that can be reached from station X.
  • If no terminal station exists(this means there exist a loop)  then print LOOP.

Constraints:

  • 0<=Q<=106
  • 1<=N<=106
  • 1<=X<=N
Time Limit: 2
Memory Limit: 256
Source Limit:
Editor Image

?