问题 L: Three Permutations

内存限制:128 MB 时间限制:1 S 标准输入输出
题目类型:传统 评测方式:文本比较 上传者:
提交:7 通过:3

题目描述

You are given three permutations a,b,c of length n. Recall that a permutation is a sequence of n integers from 1 to n, in which each number occurs exactly once.
There are three integers x,y and z. Initially, all of them equal to 1. After each second, x,y,z become ay,bz,cx respectively and simultaneously (note that the subscripts are y,z,x}).
You need to answer multiple independent queries. For each query, you are given three integers x′,y′ and z′. Tell Walk Alone the minimum time needed for tuple (x,y,z) to become (x′,y′,z′) if possible.

输入格式

The first contains an integer n (1≤n≤10^5), indicating the length of the permutations.
Each of the next three lines contains n integers. The i-th number of the second line, the third line and the fourth line indicate ai,bi and ci (1≤ai,bi,ci≤n), respectively.
The next line contains an integer Q (1≤Q≤10^5), indicating the number of queries.
Each of the next Q lines contains three integers x′,y′ and z′ (1≤x′,y′,z′≤n).

输出格式

For each query, output the minimum time needed for (x,y,z) to become (x′,y′,z′) in a line, or −1 if impossible.

输入样例 复制

5
2 1 5 4 3
3 1 4 2 5
5 4 2 1 3
5
1 1 1
2 3 5
5 5 4
3 2 3
1 4 2

输出样例 复制

0
1
2
3
4

分类标签