公式

F - Sort 解説 by en_translator


By iterating the elements from the beginning and swapping each of them with the correct one, the objective can be achieved by at most \((N-1)\) operations.

Example

5 2 3 8 4 9 6 7 1
  ↓ Move 1 to the correct position
1 2 3 8 4 9 6 7 5
  ↓ Do nothing, as 2 is already at the correct position
1 2 3 8 4 9 6 7 5
  ↓ Do nothing, as 3 is already at the correct position
1 2 3 8 4 9 6 7 5
  ↓ Move 4 to the correct position
1 2 3 4 8 9 6 7 5
  ↓ Move 5 to the correct position
1 2 3 4 5 9 6 7 8
  ↓ Move 6 to the correct position
1 2 3 4 5 6 9 7 8
  ↓ Move 7 to the correct position
1 2 3 4 5 6 7 9 8
  ↓ Move 8 to the correct position
1 2 3 4 5 6 7 8 9

If you try to find the current position of \(i\) in \(A\) every time during this procedure, it costs \(\Theta(N)\) time each at worst, for a total of \(\Theta(N^2)\) time, resulting in a TLE (Time Limit Exceeded) verdict.

Instead, in addition to the array \(A\), maintain another array \(\mathrm{pos}\) that represents the position of the value \(i\) in \(A\), and update it accordingly. For example, if \(A=(3,1,2,4)\), let \(\mathrm{pos}=(2,3,1,4)\).
This way, the current position of \(i\) in \(A\) can be referenced as \(\mathrm{pos}[i]\) in \(O(1)\) time, for a total of \(O(N)\) time to solve the entire problem.

投稿日時:
最終更新: