#P3682. Nested Dolls Transformation

    ID: 16933 Type: Default 1000ms 256MiB

Nested Dolls Transformation

Nested Dolls Transformation

In this problem, we consider a set of n wooden dolls (Matryoshka dolls) with distinct sizes. They are numbered from 1 to n in increasing order of size. Since a doll can only be directly nested inside a larger doll, if doll a is directly nested into doll b, then we call b the parent of doll a. A doll with no parent is called free. A valid nesting configuration is described by giving each doll’s parent (using 0 to denote that the doll is free).

You are allowed to perform the following two operations any number of times:

  • Detach Operation: Choose a doll that is not free (i.e. it is currently nested inside another doll) and remove it from its parent. (This operation makes the doll free.)
  • Attach Operation: Choose a free doll and nest it directly into a larger doll that is free (i.e. that is not already containing another doll). The size condition guarantees that if doll i is nested into doll j, then i < j.

Given an initial configuration and a target configuration, your task is to compute the minimum number of operations required to transform the initial configuration into the target configuration.

More formally, let \( init[i] \) and \( target[i] \) denote the parent of the ith doll in the initial and target configurations respectively (with 0 representing free). For each doll i (\(1 \leq i \leq n\)), if \( init[i] \neq target[i] \), you may need:

  • One detach operation if \( init[i] \neq 0 \) (i.e. the doll was originally nested but needs to be free in order to be reattached later or remain free).
  • One attach operation if \( target[i] \neq 0 \) (i.e. the doll needs to be nested in the target configuration).

The minimum number of operations is therefore the sum of the detach and attach operations required for each doll.

Note: In any valid configuration, since dolls are arranged from smallest to largest, the largest doll (n) must always be free.

inputFormat

The first line contains a single integer n (\(2 \le n \le 10^5\)) representing the number of dolls.

The second line contains n integers, representing the initial configuration. The ith integer is \(init[i]\) (with 0 indicating that the doll is free, and any nonzero value indicating the direct parent of doll i). It is guaranteed that if \(init[i] \neq 0\), then \(init[i] < i\) (since a doll can only be nested in a smaller-numbered, i.e. smaller, doll).

The third line contains n integers, representing the target configuration in the same format and with the same validity constraints.

outputFormat

Output a single integer: the minimum number of operations required to transform the initial configuration into the target configuration.

sample

3
0 1 0
0 0 0
1

</p>