#P11497. Warehouse Card Retrieval

    ID: 13582 Type: Default 1000ms 256MiB

Warehouse Card Retrieval

Warehouse Card Retrieval

A company is automating its warehouse. In the warehouse, there are \(n\) distinct items, numbered from \(1\) to \(n\), and each item is stored in its own room. In particular, item \(i\) is stored in room \(i\). A robot is used to retrieve items from the warehouse. The robot uses a special electronic card to enter each room. Initially, the robot has a slot containing all the cards in an order \(b_1, b_2, \dots, b_n\) (each card appears exactly once).

When the robot wants to retrieve an item, it performs the following steps to enter the corresponding room:

  1. It takes out the card at the front of the slot.
  2. If the card is not the one that opens the door to the desired room, the card is put back into the slot at any position.
  3. This process is repeated until the card at the front of the slot is the one required for the room. The robot then removes this card, uses it to enter the room, and afterwards returns the card to the slot.

If the robot takes out a total of \(x\) cards (including the final one used to open the door) to enter the room, we say that it performed \(x\) operations for that retrieval.

The robot must retrieve \(m\) items in order: \(a_1, a_2, \dots, a_m\). To minimize the total number of operations, you need to decide the positions where the robot should put the cards back after taking them out. It can be shown that the optimal strategy is to never disturb the order of the cards that have already been accessed. In particular, if for an item \(a_i\), its card has not yet been seen (i.e. its initial position in \(b\) is greater than any card accessed before), then the number of operations needed is \[ 2\times (\text{position of } a_i - \text{count of previously accessed cards}) + 1. \] Otherwise, if the card has already been seen, only 1 operation is needed. Compute the minimum total number of operations required for the robot to retrieve all \(m\) items in order.

inputFormat

The first line contains two integers \(n\) and \(m\) \((1 \leq m \leq n \leq 10^5)\), representing the number of items (and cards) and the number of retrieval operations.

The second line contains \(n\) distinct integers \(b_1, b_2, \dots, b_n\) \((1 \leq b_i \leq n)\), which denote the initial order of the cards in the slot.

The third line contains \(m\) integers \(a_1, a_2, \dots, a_m\) \((1 \leq a_i \leq n)\), indicating the order in which the items need to be retrieved.

outputFormat

Output a single integer: the minimum total number of operations the robot must perform to retrieve all \(m\) items.

sample

3 3
3 1 2
1 2 3
7