#P8094. [USACO22JAN] Cow Frisbee S

[USACO22JAN] Cow Frisbee S

Problem Description

Farmer John has N (N3×105)N\ (N\le 3\times 10^5) cows with heights 1,2,,N1, 2, \ldots, N. One day, the cows line up in some order to play frisbee. Let h1hNh_1 \ldots h_N denote the cows' heights in this order (so hh is a permutation of 1N1 \ldots N).

Two cows at positions ii and jj in the line can successfully throw a frisbee back and forth if and only if every cow between them has height less than min(hi,hj)\min(h_i, h_j).

Compute the sum of distances over all pairs of positions i<ji<j such that the two cows can successfully throw a frisbee back and forth. The distance between positions ii and jj is ji+1j-i+1.

Input Format

The first line contains an integer NN. The second line contains h1hNh_1 \ldots h_N, separated by spaces.

Output Format

Output the sum of distances between all pairs of positions i<ji<j where the cows can successfully throw a frisbee back and forth. Note that the integers in this problem may require a 64-bit integer type (for example, "long long" in C or C++).

7
4 3 1 2 5 6 7
24

Hint

【Sample Explanation】

In this example, the valid position pairs are:

(1, 2), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (4, 5), (5, 6), (6, 7)

【Constraints】

  • Testcases 1-3 satisfy N5000N\le 5000.

  • Testcases 4-11 have no additional constraints.

Translated by ChatGPT 5