Jiraiya and Rasengan Attacks

4.3

17 votes
Approved, Bit Manipulation, Exception handling, Medium, Ready
Problem

Naruto has started training from Jiraiya to develop the most powerful Rasengan attack. Jiraiya as always uses weird training exercises.

enter image description here

Jiraiya has brought a permutation P of integers. He tells Naruto to sort the permutation using minimum number of Rasengan attacks. In one Rasengan attack Naruto can choose any pair of consecutive elements of the permutation and swap it.

To make the task a little difficult, he chooses a subsegment of the permutation uniformly at random (L ≤ R) and reverses it to make . Now he asks Naruto to tell the expected number of Rasengan attacks he need to sort the permutation.

INPUT
The first line contains the integer N.
The next line contains N integers denoting the permutation P.

OUTPUT
Print where is the Expected value of number of Rasengan attacks he need to sort P (expressed as an irreducible fraction)

CONSTRAINTS

Sample Input
3
1 2 3
Sample Output
833333340
Time Limit: 1
Memory Limit: 256
Source Limit:
Explanation

The 6 ways of reversing a subarray is

  • 1,1 -> 1,2,3. Rasengan attacks = 0
  • 2,2 -> 1,2,3. Rasengan attacks = 0
  • 3,3 -> 1,2,3. Rasengan attacks = 0
  • 1,2 -> 2,1,3. Rasengan attacks = 1
  • 2,3 -> 1,3,2. Rasengan attacks = 1
  • 1,3 -> 3,2,1. Rasengan attacks = 3

Probability of getting Rasengan attacks = 0 is
Probability of getting Rasengan attacks = 1 is
Probability of getting Rasengan attacks = 3 is
Expected value of Rasengan attacks =

Editor Image

?