아직 만들고 있는 페이지입니다.

이 페이지는 아직 만드는 중입니다. 보이는 내용은 바뀔 수 있습니다.

First Last Sorting

시간 제한1초메모리 제한1024 MB

요약
1부터 n까지의 순열이 주어질 때, 맨 앞이나 맨 뒤로 옮기는 연산만으로 정렬하는 최소 횟수를 구한다.
난이도

보통10점 중 6점

유형
배열, 동적 계획법, 그리디
정답자
아직 제출이 없습니다

문제

Arup has just created a data structure that makes the two following list transformations in constant O(1) time:

  1. Take any element in the list and move it to the front.
  2. Take any element in the list and move it to the back.

You've realized that sorting speed can be improved using these transformations. For example, consider the input list:

  • 8, 3, 6, 7, 4, 1, 5, 2

We can do the following sequence of transformations to sort this list:

  • 8, 3, 7, 4, 1, 5, 2, 6 (move 6 to end)
  • 8, 3, 4, 1, 5, 2, 6, 7 (move 7 to end)
  • 2, 8, 3, 4, 1, 5, 6, 7 (move 2 to front)
  • 1, 2, 8, 3, 4, 5, 6, 7 (move 1 to front)
  • 1, 2, 3, 4, 5, 6, 7, 8 (move 8 to end)

You are now curious. Given an input array of distinct values, what is the fewest number of these first/last operations necessary to sort the array?

Given an initial permutation of the integers 1, 2, ..., n, determine the fewest number of first/last operations necessary to get the list of values sorted in increasing order.

입력

The first line of input will contain a single positive integer, n (n ≤ 105), representing the number of values to be sorted. The next n lines contain one integer each. All of these integers will be distinct values in between 1 and n (inclusive), representing the original order of the data to sort for the input case.

출력

On a line by itself, output the fewest number of first/last operations necessary to sort the input list.

예제2

  1. 예제 1

    입력
    8
    8
    3
    6
    7
    4
    1
    5
    2
    
    예상 출력
    5
    
  2. 예제 2

    입력
    5
    1
    2
    5
    3
    4
    
    예상 출력
    1