King
Time limit2sMemory limit128 MB
N elves each target a dwarf; elves enter one at a time and slide clockwise to the next free spot. Choose the entry order to maximize elven wins.
- Level
Hard8 of 10
- Topics
- Greedy, Sorting, Union-find, Implementation
- Solved
- No attempts yet
Problem
Young ruler Mirko has declared himself king of the dwarves. Slavko felt threatened by the news and declared himself king of the elves. There cannot be two kings in one land, so the two of them decided to settle the question of power for good.
Slavko takes the strongest elves of his kingdom, numbered through , to Mirko's castle. In the castle hall the strongest dwarves are sitting in a circle, numbered through clockwise.
When the elves entered, Mirko gave each of them a number , the number of the dwarf that elf will fight. He did not make sure that every elf gets a different opponent, and a terrible fight broke out.
The two rulers decided to solve the problem this way.
- Slavko sends his elves into the hall one at a time, in an order of his own choosing. The next elf enters only after the previous one has found a seat.
- Elf first walks up to dwarf . If no elf is sitting beside that dwarf, elf sits there. Otherwise elf keeps walking clockwise from dwarf to dwarf until it finds a dwarf with no elf beside it.
The resulting pairs of elves and dwarves then compete in armwrestling, and the stronger one always wins.
Slavko has studied every fighter and knows how strong each one is. He wants to send the elves into the hall in the order that gives his side the most victories once everyone is seated.
Compute the largest number of duels the elves can win.
Input
The first line contains the integer ().
The second line contains integers , the opponents chosen by Mirko ().
The third line contains integers , the strengths of the dwarves ().
The fourth line contains integers , the strengths of the elves ().
All strengths in the input are distinct.
Output
Print the largest number of duels the elves can win.
Note
In the first example Slavko can send the elves in the order . Elf sits beside dwarf , elf moves one seat clockwise and sits beside dwarf , and elf sits beside dwarf . Elves and win their duels and elf loses.