#P3253. Box Reassignment Problem

    ID: 16510 Type: Default 1000ms 256MiB

Box Reassignment Problem

Box Reassignment Problem

You are given a set of items distributed in two stacks. There are a total of \(N\) items arranged in two stacks (i.e. \(M=2\)). Each item is identical in appearance but has a unique priority. At any step you can only move the top item of a stack. In one move, you may take the top item from one stack and place it on top of the other stack. However, if the item at the top of any stack is the one with the highest priority among all items currently present, you can remove (delete) it immediately at no cost.

Your task is to determine the minimum number of moves required to remove all items from both stacks. Note that the deletion operations do not count as moves.

Important details:

  • There are \(N\) items in total.
  • Items are divided between 2 stacks. The input will specify the number of items in the first stack and the second stack respectively.
  • Items within each stack are given from top to bottom.
  • All item priorities are distinct, and an item is removable without a move if it is currently the highest priority among all items.
  • You may only move the top item of a stack. When moving an item, it becomes the new top of the destination stack.

The answer should be the minimum number of moves required so that by repeatedly moving top items (when necessary) and removing the highest‐priority top items, all items are removed.

Note: It is guaranteed that no two items have the same priority.

inputFormat

The input consists of three lines:

  1. The first line contains two non-negative integers \(n_1\) and \(n_2\) separated by a space, representing the number of items in the first and second stacks respectively.
  2. The second line contains \(n_1\) integers representing the priorities of the items in the first stack from top to bottom.
  3. The third line contains \(n_2\) integers representing the priorities of the items in the second stack from top to bottom.

outputFormat

Output a single integer, which is the minimum number of moves required to remove all items from both stacks.

sample

2 2
2 1
4 3
0