#abc302g. G - Sort from 1 to 4

G - Sort from 1 to 4

Score : 625625 points

问题描述

你得到一个长度为 NN 的序列 A=(A1,A2,,AN)A=(A_1,A_2,\ldots,A_N),其中包含 1144 之间的整数。

Takahashi 可以执行以下操作任意次数(包括零次):

  • 选择一对整数 (i,j)(i,j),满足 1i<jN1\leq i<j\leq N,然后交换 AiA_iAjA_j

找出使 AA 变为非递减所需的最少操作次数。
若对于所有 1iN11\leq i\leq N-1,均有 AiAi+1A_i\leq A_{i+1},则称该序列为非递减序列。

以上为通义千问 qwen-max 翻译,仅供参考。

Problem Statement

You are given a sequence A=(A1,A2,,AN)A=(A_1,A_2,\ldots,A_N) of length NN, consisting of integers between 11 and 44.

Takahashi may perform the following operation any number of times (possibly zero):

  • choose a pair of integer (i,j)(i,j) such that 1i<jN1\leq i<j\leq N, and swap AiA_i and AjA_j.

Find the minimum number of operations required to make AA non-decreasing.
A sequence is said to be non-decreasing if and only if AiAi+1A_i\leq A_{i+1} for all 1iN11\leq i\leq N-1.

Constraints

  • 2N2×1052 \leq N \leq 2\times 10^5
  • 1Ai41\leq A_i \leq 4
  • All values in the input are integers.

Input

The input is given from Standard Input in the following format:

NN

A1A_1 A2A_2 \ldots ANA_N

Output

Print the minimum number of operations required to make AA non-decreasing in a single line.

Sample Input 1

6
3 4 1 1 2 4

Sample Output 1

3

One can make AA non-decreasing with the following three operations:

  • Choose (i,j)=(2,3)(i,j)=(2,3) to swap A2A_2 and A3A_3, making A=(3,1,4,1,2,4)A=(3,1,4,1,2,4).
  • Choose (i,j)=(1,4)(i,j)=(1,4) to swap A1A_1 and A4A_4, making A=(1,1,4,3,2,4)A=(1,1,4,3,2,4).
  • Choose (i,j)=(3,5)(i,j)=(3,5) to swap A3A_3 and A5A_5, making A=(1,1,2,3,4,4)A=(1,1,2,3,4,4).

This is the minimum number of operations because it is impossible to make AA non-decreasing with two or fewer operations.
Thus, 33 should be printed.

Sample Input 2

4
2 3 4 1

Sample Output 2

3

update @ 2024/3/10 08:30:13