To solve this problem, we need to find the minimum number of operations required to transform a given sequence into a non-decreasing sequence using two types of operations: swapping adjacent elements and incrementing an element by 1. The solution involves a combination of these operations to minimize the total cost.
Approach
The key insight is to balance the cost of swapping elements and incrementing values. The optimal solution involves processing the elements in a way that minimizes the total cost by considering both the number of swaps and the increments required. The approach uses a Fenwick Tree (Binary Indexed Tree) to efficiently count the number of swaps needed while processing elements in a specific order.
Solution Code
python
import sys
from bisect import bisect_right
class FenwickTree:
def __init__(self, size):
self.n = size
self.tree = [0] * (self.n + 2)
def update(self, idx, delta=1):
while idx <= self.n:
self.tree[idx] += delta
idx += idx & -idx
def query(self, idx):
res = 0
while idx > 0:
res += self.tree[idx]
idx -= idx & -idx
return res
def main():
n = int(sys.stdin.readline())
a = [int(sys.stdin.readline()) for _ in range(n)]
sorted_pairs = sorted([(a[i], -i) for i in range(n)], reverse=True)
indices = [ -pair[1] for pair in sorted_pairs ]
ft = FenwickTree(n)
swap_cost = 0
for idx in indices:
swap_cost += ft.query(idx)
ft.update(idx + 1)
increment_cost = 0
prev = 0
for val, orig_idx in sorted_pairs:
current = val
if current < prev:
increment_cost += prev - current
else:
prev = current
print(swap_cost + increment_cost)
if __name__ == "__main__":
main()
Explanation
Fenwick Tree for Swap Cost: We use a Fenwick Tree to efficiently count the number of swaps required to bring each element to its correct position. By processing elements in descending order of their values (and breaking ties by their original indices in reverse order), we can compute the number of swaps needed using the Fenwick Tree.
Increment Cost Calculation: After determining the optimal order for minimizing swap costs, we calculate the increments required to ensure the sequence is non-decreasing. This is done by iterating through the sorted elements and accumulating the necessary increments whenever a value is less than the previous value in the sequence.
Combining Costs: The total cost is the sum of the swap cost (computed using the Fenwick Tree) and the increment cost (computed during the second pass through the sorted elements).
This approach efficiently balances the two types of operations to achieve the minimum total cost, leveraging sorting and Fenwick Tree operations to keep the complexity manageable for large input sizes.