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

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

Ancient Books

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

요약
각 책이 옮겨가야 할 위치를 나타내는 순열이 주어질 때, 책을 한 권만 들고 시작 위치 s에서 시작해 다시 s로 돌아오면서 모든 책을 정리하는 최소 이동 거리를 구한다.
난이도

보통10점 중 7점

유형
그래프, 유니온 파인드, 그리디
정답자
아직 제출이 없습니다

문제

The city of Tehran is home to the National Library of Iran. The main treasure of this library is located in a long hall with a row of nn tables, labeled 00 through n−1n-1 from left to right. On each table there is one ancient handwritten book being displayed. These books are ordered based on their ages, which makes it hard for the visitors to search for books by title. So, the library manager has decided to sort the books in alphabetical order of their titles.

Aryan, a librarian, is going to do the job. He has created a list pp of length nn, containing different integers from 00 to n−1n-1. This list describes the changes needed to rearrange the books into alphabetical order: for all 0≤i<n0 \leq i < n, the book that is currently on table ii should be moved to table p\[i]p\[i].

Aryan starts sorting the books at table ss. He wants to return to the same table after finishing the job. Since the books are very valuable, he cannot carry more than one book at any time. While sorting the books Aryan will perform a sequence of actions. Each of those actions has to be one of the following:

  • If he is not carrying a book and there is a book on the table he is at, he can pick up this book.
  • If he is carrying a book and there is another book on the table he is at, he can switch the book he is carrying with the one on the table.
  • If he is carrying a book and he is at an empty table, he can put the book he is carrying on the table.
  • He can walk to any table. He may carry a single book while he does so.

For all 0≤i,j≤n−10 \leq i, j \leq n - 1, the distance between tables ii and jj is precisely ∣j−i∣|j-i| meters. Your task is to compute the minimum total distance Aryan needs to walk in order to sort all the books.

제한

  • 1≤n≤1,000,0001 \le n \le 1\\,000\\,000
  • 0≤s≤n−10 \le s \le n-1
  • Array pp contains nn distinct integers between 00 and n−1n-1, inclusive.

예제

이 문제는 공개된 예제가 없습니다.