CF BUDDY
← Problems·

1172A · Nauuo and Cards

1800 · greedy, implementation

Problem: Nauuo is a girl who loves playing cards.

One day she was playing cards but found that the cards were mixed with some empty ones.

There are nn cards numbered from 11 to nn, and they were mixed with another nn empty cards. She piled up the 2n2n cards and drew nn of them. The nn cards in Nauuo's hands are given. The remaining nn cards in the pile are also given in the order from top to bottom.

In one operation she can choose a card in her hands and play it — put it at the bottom of the pile, then draw the top card from the pile.

Nauuo wants to make the nn numbered cards piled up in increasing order (the ii-th card in the pile from top to bottom is the card ii) as quickly as possible. Can you tell her the minimum number of operations?

Input Format: The first line contains a single integer nn (1n21051\le n\le 2\cdot 10^5) — the number of numbered cards.

The second line contains nn integers a1,a2,,ana_1,a_2,\ldots,a_n (0ain0\le a_i\le n) — the initial cards in Nauuo's hands. 00 represents an empty card.

The third line contains nn integers b1,b2,,bnb_1,b_2,\ldots,b_n (0bin0\le b_i\le n) — the initial cards in the pile, given in order from top to bottom. 00 represents an empty card.

It is guaranteed that each number from 11 to nn appears exactly once, either in a1..na_{1..n} or b1..nb_{1..n}.

Output Format: The output contains a single integer — the minimum number of operations to make the nn numbered cards piled up in increasing order.

Note: Example 1

We can play the card 22 and draw the card 33 in the first operation. After that, we have [0,3,0][0,3,0] in hands and the cards in the pile are [0,1,2][0,1,2] from top to bottom.

Then, we play the card 33 in the second operation. The cards in the pile are [1,2,3][1,2,3], in which the cards are piled up in increasing order.

Example 2

Play an empty card and draw the card 11, then play 11, 22, 33 in order.

Sample Cases

Case 1

Input

3
0 2 0
3 0 1

Output

2

Case 2

Input

3
0 2 0
1 0 3

Output

4

Case 3

Input

11
0 0 0 5 0 0 0 4 0 0 11
9 2 6 0 8 1 7 0 3 0 10

Output

18

Similar problems

00:00:00
Loading editor…
Welcome! I'm your coding tutor for this problem. Use the chips below to reveal stored hints or get AI feedback on your code. I'll guide you step by step — never giving away the solution.

Sign in to unlock AI tutor feedback