Minimum inversions

2.8

23 votes
Algorithms, Greedy algorithm, Greedy algorithm
Problem

There is a tree that contains n vertices and the tree is rooted at node 1. For every node such as ith node, ai is written on it. Consider the following code:

b := an array of length n
time := 1

procedure DFS(T, a, v):
    b[time] = a[v]
    time += 1
    label v as visited
    for u in T.neighbors(v) do:
        if not visited[u] do:
            DFS(T, a, u)
        end if
    end for
end procedure

procedure countInversions()
    DFS(T, a, 1)
    return number of inversions in the array b
    /* Number of inversions in the array b is the number of distinct pairs (i, j) such that 1 <= i < j <= n and b[i] > b[j] */
end procedure

You are required to call countInversions. The return value of the function depends on the order of children attached to vertices. Determine the minimum return value of countInversions over all possible ordering of children attached to vertices, print this order.

Input format

  • First line: n
  • Second line: a1, a2, , an
  • Third line: p2, p3, , pn where pi is the parent of the vertex i in the tree

Output format

Determine the minimum return value of countInversions over all possible ordering of children of vertices and print the order. You are required to print n lines. In the ith line, print the order of children of vertex i. If vertex i does not contain any children, then print 0.

Constraints

1n1061ai1061pi<i

Scoring

Arrays a,p are generated randomly

Time Limit: 1.5
Memory Limit: 256
Source Limit:
Explanation

b = {0, 0, 0, 2, 0, 2}. Number of inversions is equal to 1.

Editor Image

?