#P11197. Consistent Dog Race Order Pairs

    ID: 13263 Type: Default 1000ms 256MiB

Consistent Dog Race Order Pairs

Consistent Dog Race Order Pairs

There are N dogs competing in a dog race, and three people have each guessed the finishing order. Let the final finishing order be a permutation \(T\) of \(\{1,2,\dots,N\}\), where \(T[i]\) is the dog that finished in the \(i\text{-th}\) position. For each person \(j\) (with \(1 \le j \le 3\)), their guess is represented by a permutation \(P(j)\) of \(\{1,2,\dots,N\}\). It is guaranteed that there are no ties in any ordering.

We are interested in counting the number of ordered pairs \((a,b)\) of distinct dogs such that:

  1. In the final order \(T\), dog \(a\) finishes before dog \(b\) (i.e. \(a\) appears before \(b\) in \(T\));
  2. Across all three guesses, the relative order of \(a\) and \(b\) is consistent. Formally, either for every \(1 \le j \le 3\), dog \(a\) appears before dog \(b\) in \(P(j)\), or for every \(1 \le j \le 3\), dog \(b\) appears before dog \(a\) in \(P(j)\).

Your task is to compute the number of such pairs \((a,b)\).

Note: The guessed orders may not necessarily agree with the final order \(T\); they only need to be mutually consistent for the particular pair \((a, b)\) to be counted.

inputFormat

The first line contains an integer \(N\) (the number of dogs).
The second line contains \(N\) distinct integers \(T[1], T[2], \dots, T[N]\), representing the final finishing order of the dogs.
The following three lines each contain \(N\) distinct integers. The \(j\)-th of these lines represents the guessed order \(P(j)\) provided by the \(j\)-th person.

outputFormat

Output a single integer: the number of pairs \((a,b)\) that satisfy the conditions.

sample

3
1 2 3
1 2 3
1 2 3
1 2 3
3