This page is still under construction.

Parts of this page are still being built. What you see may change.

Special graph

Time limit1sMemory limit64 MB

Summary
Edge deletions hit a functional graph while queries ask for the directed distance from a to b along the single outgoing walk.
Level

Hard8 of 10

Topics
Graph, Tree, Union-find
Solved
No attempts yet

Problem

You are given a directed graph with NN vertices. The graph is special because every vertex has at most one outgoing edge. Process two kinds of queries.

  • 1 a: delete the edge going out of vertex aa. This edge is guaranteed to exist.
  • 2 a b: print the length of the shortest path from vertex aa to vertex bb. If there is no such path, print -1.

The length of a path is the number of edges on it. Since a vertex has at most one outgoing edge, only one walk starts at aa, and the answer is the number of edges you follow along that walk until you first reach bb. If aa and bb are the same, the answer is 0.

Input

The first line contains the number of vertices NN (1≤N≤1051 \le N \le 10^5).

The second line contains NN integers next1,next2,…,nextNnext_1, next_2, \dots, next_N (0≤nexti≤N0 \le next_i \le N). The value nextinext_i means there is an edge from vertex ii to vertex nextinext_i. If nexti=0next_i = 0, vertex ii has no outgoing edge.

The third line contains the number of queries MM (1≤M≤1051 \le M \le 10^5).

Each of the next MM lines contains one query in the format described above, with 1≤a,b≤N1 \le a, b \le N.

Output

For each 2 a b query, print one answer per line, in the order the queries are given.

Examples2

  1. Example 1

    Input
    6
    3 3 4 5 6 4
    6
    2 1 6
    2 1 4
    2 1 2
    1 3
    2 1 6
    2 1 4
    2 1 3
    
    Expected output
    4
    2
    -1
    -1
    -1
    
  2. Example 2

    Input
    4
    4 4 1 3
    5
    2 2 4
    2 2 1
    1 4
    1 2
    2 3 1
    
    Expected output
    1
    3
    1