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

#FT0000036. Sắp xếp các lá bài (Cards Sorting)

HỌC THEO LỘ TRÌNH

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

1 lộ trình

Sắp xếp các lá bài (Cards Sorting)

Cards Sorting

Source: Codeforces

Version: Phuoc Hung OJ Extended

Problem Statement

Vasily has a stack of nn cards, initially arranged from top to bottom in the given order. Every card has an integer value; equal values are allowed.

He repeatedly looks at the top card; every such look counts as one inspection. If its value is the minimum among all cards still in the stack, he permanently removes it. Otherwise, he puts it at the bottom, preserving the order of the other cards.

The process ends when the stack is empty. Find the total number of top-card inspections, including cards inspected and moved to the bottom instead of removed. This number may exceed nn.

Input

  • Line 1: integer nn, the number of cards.
  • Line 2: nn integers a1,a2,…,ana_1,a_2,\ldots,a_n, ordered from top to bottom.

Output

Print one integer: the total number of times the top card is inspected before the stack becomes empty.

Subtasks

Subtask 1 (20 points):

  • 1≤n≤201\le n\le 20; 1≤ai≤1000001\le a_i\le 100000 for every 1≤i≤n1\le i\le n.

Subtask 2 (30 points):

  • 1≤n≤20001\le n\le 2000; 1≤ai≤1000001\le a_i\le 100000 for every 1≤i≤n1\le i\le n.

Subtask 3 (50 points):

  • 1≤n≤1000001\le n\le 100000; 1≤ai≤1000001\le a_i\le 100000 for every 1≤i≤n1\le i\le n.

Examples

Examples 1

Input

4
6 3 1 2

Output

7

Explanation

Starting with [6,3,1,2][6,3,1,2], inspect 66, 33, then 11; only 11 is removed (3 inspections). The remaining order is [2,6,3][2,6,3]. Inspect and remove 22 (4th), inspect 66 and move it, inspect and remove 33 (5th and 6th), and finally remove 66 on the 7th inspection.

Examples 2

Input

7
3 3 3 3 3 3 3

Output

7

Explanation

Every card has the current minimum value 33, so each inspection immediately removes one card. Exactly 77 inspections are needed.

No card has a value below 33, so the first card examined is always eligible for removal. The remaining six, then five, and so on, still all have value 33. Exactly one examination removes each card, giving 77 examinations in total.