Swapping numbers

3.1

21 votes
Datastructures, Fenwick (Binary Indexed) Trees, Inversion Count, Fenwick Tree, Advanced Data Structures, Data Structures, Segment tree
Problem

You are given a permutation p1,p2,...,pn of numbers from 1 to n.

A permutation p1,p2,...,pn, beauty, is defined as the minimum number of adjacent swaps required to sort the permutation.

If it is allowed to swap two elements of the permutation (not necessarily adjacent) at most once, then what is the minimum beauty that you can get?

Input format

  • The first line contains n.
  • The second line contains the space-separated permutation p1,p2,...,pn.

Output format

Print an integer denoting the minimum ugliness that we can get.

Constraints

1n7000

1pin, all pi are distinct

Time Limit: 1
Memory Limit: 256
Source Limit:
Explanation

After swapping p2 and p4, the permutation becomes: 1,3,2,4,5.
And it can be sorted by just swapping p2 and p3. so its ugliness is 1.
 

Editor Image

?