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

#FT0000147. Các đường đi cắt nhau trên vòng tròn (Circle Cross)

HỌC THEO LỘ TRÌNH

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

1 lộ trình

Các đường đi cắt nhau trên vòng tròn (Circle Cross)

Circle Cross

Source: USACO

Version: Phuoc Hung OJ Extended

Problem Statement

There are nn cows with distinct identifiers 11 through nn. Each cow crosses a circular road at exactly two distinct positions. The 2n2n positions are all different. Reading clockwise around the circle yields a sequence of 2n2n cow identifiers, in which each identifier appears exactly twice.

The two paths for different cows necessarily cross precisely when their endpoints alternate around the circle. Equivalently, between the two occurrences of one cow there is exactly one occurrence of the other cow. Count the number of unordered pairs of cows whose paths cross; count each pair once.

Input

The first line contains nn. The following 2n2n integers (which may be on separate lines) are the cow IDs in clockwise order.

Output

Print one integer: the number of crossing cow pairs.

Subtasks

  • Subtask 1 (20 points): 1≤n≤101\le n\le 10; the sequence has 2n2n IDs in [1,n][1,n], each occurring exactly twice.
  • Subtask 2 (30 points): 1≤n≤30001\le n\le 3000; the sequence has 2n2n IDs in [1,n][1,n], each occurring exactly twice.
  • Subtask 3 (50 points): 1≤n≤500001\le n\le 50000; the sequence has 2n2n IDs in [1,n][1,n], each occurring exactly twice.

Examples

Example 1

Input

4
3
2
4
4
1
3
2
1

Output

3

Explanation

The occurrence positions are cow 1: (5,8)(5,8), cow 2: (2,7)(2,7), cow 3: (1,6)(1,6), and cow 4: (3,4)(3,4). Alternating endpoint pairs are (1,2)(1,2), (1,3)(1,3) and (2,3)(2,3). Cow 4 has adjacent endpoints and crosses nobody, yielding 3 pairs.

Example 2

Input

3
1
2
1
3
2
3

Output

2

Explanation

Cows 1 and 2 have endpoints (1,3)(1,3) and (2,5)(2,5), so these endpoints alternate. Cows 2 and 3 have (2,5)(2,5) and (4,6)(4,6), also alternating. Cows 1 and 3 do not alternate. Hence exactly 2 crossing pairs.