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

#FT0000063. Số giao cắt lớn nhất của hệ dây dẫn (Maximum Crossings (Hard Version))

HỌC THEO LỘ TRÌNH

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

1 lộ trình

Số giao cắt lớn nhất của hệ dây dẫn (Maximum Crossings (Hard Version))

Maximum Crossings (Hard Version)

Source: Codeforces

Version: Phuoc Hung OJ Extended

Problem Statement

There are two terminals, each consisting of nn equal segments ordered from left to right and numbered starting at 11. One terminal is above the other.

The array a1,a2,…,ana_1,a_2,\ldots,a_n requires a straight wire from the interior of upper segment ii to the interior of lower segment aia_i. You may freely choose the endpoints within the segments but cannot place them at a segment boundary.

Two wires cross if they share a point. Place the endpoints to maximize the number of crossing pairs of wires. Equal values of aia_i are allowed; wires arriving at the same lower segment may still be made to cross.

Input

The first line contains nn.

The second line contains nn integers a1,a2,…,ana_1,a_2,\ldots,a_n, the destination lower segments.

Output

Print the maximum achievable number of crossing wire pairs.

Subtasks

  • Subtask 1 (20 points): 1≤n≤601\le n\le 60; 1≤ai≤n1\le a_i\le n for every element.

  • Subtask 2 (30 points): 1≤n≤30001\le n\le 3000; 1≤ai≤n1\le a_i\le n for every element.

  • Subtask 3 (50 points): 1≤n≤2000001\le n\le 200000; 1≤ai≤n1\le a_i\le n for every element.

Examples

Input

3
2 2 2

Output

3

Explanation

All three wires lead to lower segment 22. Place their endpoints on that segment in the reverse order of their upper positions. Then wires 11 and 22, 11 and 33, and 22 and 33 cross.

There are exactly (32)=3\binom{3}{2}=3 wire pairs, so no arrangement can have more than 33 crossings. The answer is 3.