PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#FT0000043. Làm rỗng mảng (Make Array Empty)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Làm rỗng mảng (Make Array Empty)

Make Array Empty

Source: LeetCode

Version: Phuoc Hung OJ Extended

Problem Statement

You are given an array aa of nn pairwise distinct integers. Repeatedly perform one of the following operations until the array becomes empty:

  • If the current first element is the minimum of the entire remaining array, remove it.
  • Otherwise, move the current first element to the end, preserving the relative order of the other elements.

Each action counts as one operation, including moving an element without removing it. After every operation, apply the rule to the updated array. Return the total number of operations. Because the input values are distinct, the current minimum is unique.

Input

  • Line 1: integer nn, the array length.
  • Line 2: exactly nn integers a1,a2,…,ana_1,a_2,\ldots,a_n in initial order.

Output

Print one integer: the total number of operations required to empty the array.

Subtasks

Subtask 1 (20 points):

  • 1≤n≤201\le n\le 20; −109≤ai≤109-10^9\le a_i\le 10^9 for all 1≤i≤n1\le i\le n; ai≠aja_i\ne a_j for i≠ji\ne j.

Subtask 2 (30 points):

  • 1≤n≤20001\le n\le 2000; −109≤ai≤109-10^9\le a_i\le 10^9 for all 1≤i≤n1\le i\le n; ai≠aja_i\ne a_j for i≠ji\ne j.

Subtask 3 (50 points):

  • 1≤n≤1000001\le n\le 100000; −109≤ai≤109-10^9\le a_i\le 10^9 for all 1≤i≤n1\le i\le n; ai≠aja_i\ne a_j for i≠ji\ne j.

Examples

Examples 1

Input

3
3 4 -1

Output

5

Explanation

Start with [3,4,−1][3,4,-1]. Move 33 to the end (step 1), then move 44 to the end (step 2), reaching [−1,3,4][-1,3,4]. Remove −1-1 (step 3), then 33 (step 4), and finally 44 (step 5).

Examples 2

Input

4
1 2 4 3

Output

5

Explanation

Remove 11 and 22 immediately (2 steps), leaving [4,3][4,3]. Rotate 44 to the end (step 3), remove 33 (step 4), and remove 44 (step 5).

The complete sequence of states is $[1,2,4,3] \to [2,4,3] \to [4,3] \to [3,4] \to [4] \to []$. The first two, fourth, and last transitions remove an element; the third moves 44 to the back. This makes four removals and one move, for 55 operations.