#P6288. Duel of the Realms
Duel of the Realms
Duel of the Realms
Dwarf Kingdom and Elf Kingdom are on the brink of war! The Elf King Slavko has numbered his n elves from $1$ to $n$. The Dwarf King Mirko has arranged his n dwarfs in a circle and numbered them in clockwise order starting from an arbitrary dwarf as $1,\dots,n$.
Mirko then assigns each elf a number $a_i$ ($1\le a_i\le n$) which indicates the dwarf that is ideally chosen as that elf's opponent. Due to his carelessness the same number may be assigned to more than one elf.
To ensure fairness, the following procedure is used to determine the duel pairings:
- Slavko selects an elf who has not yet been assigned an opponent. Let its index be $i$.
- If the dwarf with index $a_i$ has not yet been paired then that dwarf is chosen as the opponent. Otherwise, starting from dwarf $a_i$, the first unpaired dwarf in clockwise order is chosen.
- This is repeated until every elf and every dwarf has been paired.
Each elf and dwarf has a power value. In a duel the side with the higher power always wins. Knowing the power values of all elves and dwarfs, Slavko wants to know: by choosing the order in which elves are processed optimally, what is the maximum number of duels that the elves can win?
The twist is that although each elf has a mandatory starting position $a_i$, Slavko can decide the processing order of elves. With a proper ordering, the final pairing is uniquely determined by the following observation:
For any chosen starting index r (which is effectively the beginning of the circular order for both dwarfs and the elf starting positions), define the adjusted starting position of an elf with given $a_i$ as:
$$\text{key}_i = \begin{cases} a_i, & \text{if } a_i \ge r, \\ a_i+n, & \text{if } a_i < r. \end{cases} $$If we sort the elves by their adjusted starting position and pair them with dwarfs taken in the cyclic order starting from r (i.e. the list $[D_r, D_{r+1},\dots,D_n, D_1,\dots, D_{r-1}]$), then the pairing produced is exactly the one obtained by the above procedure when Slavko processes elves in that order. An elf wins if its power is greater than the power of the dwarf it is paired with.
Your task is to compute the maximum number of wins the elves can achieve by choosing an optimal processing order (equivalently, an optimal rotation r).
inputFormat
The first line contains a single integer n ($1\le n\le 2000$) --- the number of elves (and dwarfs).
The second line contains n integers $a_1,a_2,\dots,a_n$ ($1\le a_i\le n$), where $a_i$ is the preferred dwarf index for the i-th elf.
The third line contains n integers, where the i-th integer is the power of the i-th elf.
The fourth line contains n integers, where the i-th integer is the power of the i-th dwarf.
outputFormat
Output a single integer --- the maximum number of duels that the elves can win.
sample
2
1 1
10 1
5 9
1