Almost Bubble Sort

AtCoder
IDawtf2024_d
Time10000ms
Memory256MB
Difficulty
You are given a permutation $P=(P_1,P_2,\cdots,P_N)$ of $(1,2,\cdots,N)$. You want to perform zero or more swaps of adjacent elements so that $P$ satisfies the following condition: * The number of indices $i$ such that $P_i > P_{i+1}$ is at most $1$. Find the minimum number of swaps required. ## Constraints * $2 \leq N \leq 800000$ * $(P_1,P_2,\cdots,P_N)$ is a permutation of $(1,2,\cdots,N)$. * All input values are integers. ## Input The input is given from Standard Input in the following format: $N$ $P_1$ $P_2$ $\cdots$ $P_N$ [samples]
Samples
Input #1
3
3 2 1
Output #1
1

Swapping $P_1$ and $P_2$ turns $P$ into $(2,3,1)$, which satisfies the condition.
Input #2
4
2 4 1 3
Output #2
0
Input #3
6
2 3 1 6 4 5
Output #3
1
Input #4
20
8 13 6 11 20 3 12 18 17 4 10 1 7 16 19 5 2 15 14 9
Output #4
36
API Response (JSON)
{
  "problem": {
    "name": "Almost Bubble Sort",
    "description": {
      "content": "You are given a permutation $P=(P_1,P_2,\\cdots,P_N)$ of $(1,2,\\cdots,N)$. You want to perform zero or more swaps of adjacent elements so that $P$ satisfies the following condition: *   The number of ",
      "description_type": "Markdown"
    },
    "platform": "AtCoder",
    "limit": {
      "time_limit": 10000,
      "memory_limit": 262144
    },
    "difficulty": "None",
    "is_remote": true,
    "is_sync": true,
    "sync_url": null,
    "sign": "awtf2024_d"
  },
  "statements": [
    {
      "statement_type": "Markdown",
      "content": "You are given a permutation $P=(P_1,P_2,\\cdots,P_N)$ of $(1,2,\\cdots,N)$.\nYou want to perform zero or more swaps of adjacent elements so that $P$ satisfies the following condition:\n\n*   The number of ...",
      "is_translate": false,
      "language": "English"
    }
  ]
}
Full JSON Raw Segments