Two Pointers (hard version)

면접 대비

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

요약
두 운전자가 A와 B에서 출발해 n개의 이벤트를 순서대로 방문할 때 총 이동 거리의 최솟값을 구한다.
난이도

보통10점 중 7점

유형
동적 계획법, 배열, 투 포인터, 수학
정답자
아직 제출이 없습니다

문제

Alice and Bob are driving on a very long road that stretches from points −109-10^9 to 10910^9. Alice starts at point AA while Bob starts at point BB. There are nn events to visit, where event ii is at position t_it\_i. Either Alice or Bob must visit each event, but they must be visited in order (they must visit event 11, then event 22, then event 33, \dots then event nn).

Find the minimum total distance Alice and Bob can drive to visit all events.

입력

The first line contains a single integer nn (1≤n≤3⋅1051\le n\le3\cdot10^5) --- the number of events.

The second line contains two integers AA and BB (−109≤A,B≤109-10^9\le A,B\le10^9) --- Alice and Bob's starting points.

The third line contains nn integers t_1,t_2,…,t_nt\_1,t\_2,\dots,t\_n (−109≤t_i≤109-10^9\le t\_i\le10^9) --- the locations of events either Alice or Bob must get to.

출력

Output an integer --- the minimum total distance Alice and Bob drive.

힌트

In the first example:

  • Bob moves from position 33 to position 55 to attend event 11, driving 22 units.
  • Alice moves from position 22 to position 11 to attend event 22, driving 11 unit.
  • Bob moves from position 55 to position 44 for event 33, driving 11 unit.
  • Bob stays at position 44, attending event 44, driving 00 units.
  • Bob moves from position 44 to position 77 for event 55, driving 33 units.

The total distance travelled is 2+1+1+0+3=72+1+1+0+3=7.

In the second example, Alice visits all events.

예제3

  1. 예제 1

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

    입력
    6
    540 152
    450 600 532 496 325 336
    
    예상 출력
    526
    
  3. 예제 3

    입력
    8
    35 315
    -406 -543 114 205 -840 161 540 -731
    
    예상 출력
    1699