To solve this problem, we need to transform a given sequence into a non-decreasing sequence with the minimum number of operations. The allowed operations are swapping adjacent elements and incrementing an element by 1. The goal is to minimize the total number of operations (swaps and increments).
Approach
The key insight is to use a priority queue (min-heap) to efficiently track and select the best elements for each position while considering both the swap and increment costs. Here's the detailed approach:
Priority Queue (Min-Heap): We use a min-heap to keep track of the elements that can be placed at the current position. Each element in the heap is adjusted by its original position to account for the swap cost.
Greedy Selection: For each position, we select the element that minimizes the total cost, considering both the swap cost (distance from its original position) and the increment cost (difference between the required value and the element's current value).
Required Value Tracking: Maintain the required value for the current position to ensure the sequence remains non-decreasing. This required value is the maximum of the previous required value plus 1 and the selected element's value.
Solution Code
python
import heapq
n = int(input())
a = [int(input()) for _ in range(n)]
heap = []
ans = 0
current = 0
for i in range(n):
heapq.heappush(heap, (a[i] - i, i)) # Adjusted value for swap cost
while True:
val, pos = heapq.heappop(heap)
if pos >= i:
required = max(current + 1, val + i)
ans += (pos - i) + (required - (val + i))
current = required
heapq.heappush(heap, (val, pos)) # Re-insert for future positions
break
print(ans)
Explanation
Heap Initialization: Each element is added to the heap with an adjusted value a[i] - i to account for its original position. This adjustment helps in minimizing the swap cost when elements are moved left.
Element Selection: For each position i, the element with the smallest adjusted value is selected. This ensures that the swap cost (original position minus current position) and the increment cost (required value minus element's adjusted value) are minimized.
Required Value Calculation: The required value for the current position is determined to ensure the sequence remains non-decreasing. This value is the maximum of the previous required value plus 1 and the element's adjusted value plus its current position.
Cost Calculation: The total cost is the sum of the swap cost and the increment cost for each selected element. The heap is reinitialized to ensure all elements are considered for subsequent positions.
This approach efficiently balances swap and increment operations to achieve the minimum total cost, ensuring the sequence becomes non-decreasing with optimal operations.