Gathering Sharks

시간 제한2초메모리 제한2048 MB

요약
서로 다른 번호가 붙은 n마리의 상어가 일렬로 있을 때, 번호 b인 그룹을 b보다 작은 번호 중 가장 큰 그룹으로 합치는 명령을 반복해 모두 한 점에 모으는 최소 시간을 구한다.
난이도

어려움10점 중 8점

유형
동적 계획법, 그리디, 구현, 수학
정답자
아직 제출이 없습니다

문제

You are the leader of a swarm of nn sharks living in a one-dimensional ocean. The sharks are positioned from left to right, with each adjacent pair separated by a distance of one unit.

As the leader, you want all the sharks to gather at a common point to form a single group. Initially, no two sharks belong to the same group; for each i=1,…,ni = 1, \dots , n, the ii-th shark from the left forms its own group, uniquely numbered a_ia\_i, consisting of only itself.

To achieve your goal, you can command the sharks to perform the following actions n−1n − 1 times.

  1. You shout out an integer bb that meets both conditions:

    • There exists a group numbered bb.
    • There exists at least one group numbered strictly smaller than bb.
  2. Afterward, letting cc be the largest existing group number strictly smaller than bb, all the sharks in the group numbered bb simultaneously move to the position of the group numbered cc, and the two groups merge.

  3. The merged group is numbered bb, and the group numbered cc ceases to exist.

All sharks move at a constant speed of one unit distance per unit time. Commands must be executed sequentially, with no overlap in execution. Once a command is completed, the next one can begin immediately.

Compute the minimum time required for all the sharks to gather at a common point by commanding the sharks n−1n − 1 times optimally.

입력

The first line of input contains an integer nn (2≤n≤5002 ≤ n ≤ 500). The second line contains nn pairwise distinct integers a_1,a_2,…,a_na\_1, a\_2, \dots , a\_n (1≤a_i≤n1 ≤ a\_i ≤ n).

출력

Output the minimum time required for all the sharks to gather at a common point.

예제2

  1. 예제 1

    입력
    4
    3 2 4 1
    
    예상 출력
    4
    
  2. 예제 2

    입력
    9
    1 2 4 5 7 8 3 6 9
    
    예상 출력
    17