PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#FT0000204. Số nghịch thế kỳ vọng sau khi xáo trộn (Inversions After Shuffle)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Số nghịch thế kỳ vọng sau khi xáo trộn (Inversions After Shuffle)

Inversions After Shuffle

Source: Codeforces

Version: Phuoc Hung OJ Extended

Problem Statement

You are given a permutation a1,a2,…,ana_1,a_2,\ldots,a_n of the integers from 11 to nn.

Perform exactly one random experiment:

  1. Choose a contiguous segment [l,r][l,r], where 1≤l≤r≤n1\le l\le r\le n. All n(n+1)/2n(n+1)/2 possible segments are equally likely.
  2. Randomly permute the values inside [l,r][l,r], assigning equal probability to every ordering of those values. The elements outside the segment remain unchanged.

An inversion is a pair of indices i<ji<j with ai>aja_i>a_j. Compute the expected number of inversions after the experiment. The required answer is a real number, not a permutation.

Input

  • The first line contains the permutation length nn.
  • The second line contains exactly nn integers a1,a2,…,ana_1,a_2,\ldots,a_n, each integer from 11 to nn appearing exactly once.

Output

Print one real number: the expected number of inversions. An absolute or relative error at most 10−910^{-9} is accepted. You may print enough decimal digits to meet this precision.

Subtasks

  • Subtask 1 (20 points): 1≤n≤81\le n\le 8; aa is a permutation of 1,…,n1,\ldots,n; absolute or relative error at most 10−910^{-9}.
  • Subtask 2 (30 points): 1≤n≤20001\le n\le 2000; aa is a permutation of 1,…,n1,\ldots,n; absolute or relative error at most 10−910^{-9}.
  • Subtask 3 (50 points): 1≤n≤1051\le n\le 10^5; aa is a permutation of 1,…,n1,\ldots,n; absolute or relative error at most 10−910^{-9}.

Examples

Input

3
2 3 1

Output

1.916666666666666666666666666667

Explanation

For a=[2,3,1]a=[2,3,1], initially the pairs (1,3)(1,3) and (2,3)(2,3) are inversions, so there are two.

There are six equally likely segments. Each of the three length-one segments keeps the inversion count at 22. Segment [1,2][1,2] gives expectation 2+1/2=5/22+1/2=5/2. Segment [2,3][2,3] replaces one internal inversion by an expected 1/21/2, giving 3/23/2. Segment [1,3][1,3] gives an expected 1/21/2 per pair of positions, or 3/23/2 in total.

The six expectations add to 2+2+2+5/2+3/2+3/2=23/22+2+2+5/2+3/2+3/2=23/2. Dividing by six gives 23/12=1.9166666666…23/12=1.9166666666\ldots, matching the sample output.