atcoder#APC001H. Generalized Insertion Sort

Generalized Insertion Sort

Score : 20002000 points

Problem Statement

You are given a rooted tree with NN vertices. The vertices are numbered 0,1,...,N10, 1, ..., N-1. The root is Vertex 00, and the parent of Vertex ii (i=1,2,...,N1)(i = 1, 2, ..., N-1) is Vertex pip_i.

Initially, an integer aia_i is written in Vertex ii. Here, (a0,a1,...,aN1)(a_0, a_1, ..., a_{N-1}) is a permutation of (0,1,...,N1)(0, 1, ..., N-1).

You can execute the following operation at most 2525 000000 times. Do it so that the value written in Vertex ii becomes ii.

  • Choose a vertex and call it vv. Consider the path connecting Vertex 00 and vv.
  • Rotate the values written on the path. That is, For each edge (i,pi)(i, p_i) along the path, replace the value written in Vertex pip_i with the value written in Vertex ii (just before this operation), and replace the value of vv with the value written in Vertex 00 (just before this operation).
  • You may choose Vertex 00, in which case the operation does nothing.

Constraints

  • 2N20002 \leq N \leq 2000
  • 0pii10 \leq p_i \leq i-1
  • (a0,a1,...,aN1)(a_0, a_1, ..., a_{N-1}) is a permutation of (0,1,...,N1)(0, 1, ..., N-1).

Input

Input is given from Standard Input in the following format:

NN

p1p_1 p2p_2 ... pN1p_{N-1}

a0a_0 a1a_1 ... aN1a_{N-1}

Output

In the first line, print the number of operations, QQ. In the second through (Q+1)(Q+1)-th lines, print the chosen vertices in order.

5
0 1 2 3
2 4 0 1 3
2
3
4
  • After the first operation, the values written in Vertex 0,1,..,40, 1, .., 4 are 4,0,1,2,34, 0, 1, 2, 3.
5
0 1 2 2
4 3 1 2 0
3
4
3
1
  • After the first operation, the values written in Vertex 0,1,..,40, 1, .., 4 are 3,1,0,2,43, 1, 0, 2, 4.
  • After the second operation, the values written in Vertex 0,1,..,40, 1, .., 4 are 1,0,2,3,41, 0, 2, 3, 4.