Under construction

Still being built. Things may change

Generalized Insertion Sort

Time limit2sMemory limit256 MB

Summary
Given a rooted tree with a permutation on its vertices, sort the values using at most 25,000 path-rotation operations from the root to a chosen vertex.
Level

Hard8 of 10

Topics
Tree, Simulation, Sorting
Solved
No attempts yet

Problem

You are given a rooted tree with NN vertices, numbered 0,1,…,N−10, 1, \ldots, N-1. The root is vertex 00, and the parent of vertex ii (i=1,2,…,N−1i = 1, 2, \ldots, N-1) is vertex pip_i.

Initially, vertex ii holds the integer aia_i. Here, (a0,a1,…,aN−1)(a_0, a_1, \ldots, a_{N-1}) is a permutation of (0,1,…,N−1)(0, 1, \ldots, N-1).

You can perform the following operation at most 25 00025\,000 times. The goal is to make the value at vertex ii equal to ii for every ii.

  • Choose a vertex vv. Consider the path from vertex 00 to vv.
  • Rotate the values on this path. For each edge (i,pi)(i, p_i) on the path, the value at pip_i becomes the value at ii (before this operation), and the value at vv becomes the value at 00 (before this operation).
  • Choosing vertex 00 does nothing.

Input

Input is given in the following format:

NN

p1p_1 p2p_2 ... pN−1p_{N-1}

a0a_0 a1a_1 ... aN−1a_{N-1}

Output

In the first line, print the number of operations QQ. In the next QQ lines, print the chosen vertices in order.

Constraints

2≤N≤20002 \leq N \leq 2000, 0≤pi≤i−10 \leq p_i \leq i-1, and (a0,a1,…,aN−1)(a_0, a_1, \ldots, a_{N-1}) is a permutation of (0,1,…,N−1)(0, 1, \ldots, N-1).

Hint

In Sample 1, after the first operation, the values at vertices 0,1,…,40, 1, \ldots, 4 are 4,0,1,2,34, 0, 1, 2, 3.

In Sample 2, after the first operation, the values at vertices 0,1,…,40, 1, \ldots, 4 are 3,1,0,2,43, 1, 0, 2, 4. After the second operation, they are 1,0,2,3,41, 0, 2, 3, 4.

Examples2

  1. Example 1

    Input
    5
    0 1 2 3
    2 4 0 1 3
    
    Expected output
    2
    3
    4
    
  2. Example 2

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