Bad Hair Day and Expected Value
Time limit2sMemory limit512 MB
Given N cows with heights, count the expected number of visible pairs over all N! orderings, modulo 1e9+7.
- Level
Medium7 of 10
- Topics
- Combinatorics, Math, Sorting, Stack
- Solved
- No attempts yet
Problem
Farmer John has N cows. Their heights vary, and two cows may have the same height.
The cows dislike their hairstyles, so they line up to check each other's hairstyles.
Each cow looks to her right and can check the hairstyles of all cows that appear before a cow at least as tall as herself shows up. More precisely, if the height of the cow standing at position i from the left is *H'*i, then cow i can see cow j when, and only when, the following conditions hold.
- i < j and *H'*i > *H'*j.
- There is no k with i < k < j and *H'*i ≤ *H'*k.
Since there are N cows, the number of ways they can line up is N!. Farmer John wants to know the expected number of pairs of cows that can check each other's hairstyles. Write a program that helps Farmer John print this expected value.
Input
The first line gives N, a positive integer that indicates the number of cows.
The second line gives N positive integers H1, ..., HN, the heights of the N cows, separated by spaces.
Output
Suppose two coprime nonnegative integers and satisfy that the expected number of pairs of cows that can check each other's hairstyles equals . Find the integer with such that , and print it on the first line.
There always exist , , and that satisfy the conditions. is also guaranteed to be unique.
Constraints
Every input satisfies the following conditions.
- 1 ≤ N ≤ 2 × 105
- 1 ≤ Hi ≤ 109 (1 ≤ i ≤ N)