Train

Interview

Time limit1sMemory limit512 MB

Summary
Count the fewest round trips a train needs to drop its wagons from the back at their assigned cities in order.
Level

Medium4 of 10

Topics
Greedy, Hash map
Solved
No attempts yet

Problem

Every year a large shipment of raw materials arrives at an island. The materials are brought to the port, and from there they are delivered by train to every city on the island. All cities lie along the coast and are numbered consecutively from 11 to nn. The train's route runs all the way around the island, passing through every city.

The train is a single locomotive pulling a number of wagons. Each wagon carries a different kind of raw material, and each city receives a different material. There are exactly as many wagons as there are cities. Normally the wagons are arranged so that at each city the train drops off its last wagon and moves on to the next city, finishing every delivery in a single loop. This time, however, the materials were labeled incorrectly and the order of the wagons got mixed up.

The engineer wants to know the minimum number of loops needed to deliver every material to its correct city, given that he can only ever detach the last wagon and can never reattach a wagon once it has been dropped off. The start and end station is city 11, where the port is located. A new loop begins the moment the train sets off toward city 22.

Input

The first line contains one integer nn (2≤n≤1062 \le n \le 10^6), the number of cities on the island. The second line contains nn integers w1,w2,…,wnw_1, w_2, \dots, w_n (1≤wi≤1061 \le w_i \le 10^6, and wi≠wjw_i \ne w_j whenever i≠ji \ne j), where wiw_i is the kind of raw material loaded in the ii-th wagon counting from the locomotive. The third line contains nn pairwise distinct integers m1,m2,…,mnm_1, m_2, \dots, m_n, where mim_i is the material ordered by city ii, for i=1,2,…,ni = 1, 2, \dots, n. The numbers on the second and third lines are separated by single spaces. You may assume the two sets are equal: {w1,w2,…,wn}={m1,m2,…,mn}\{w_1, w_2, \dots, w_n\} = \{m_1, m_2, \dots, m_n\}.

Output

Print one integer: the minimum number of loops needed to deliver every material to its correct city.

Hint

Explanation: The figure above shows a case with 55 cities. In the first loop only the wagon carrying material 55 is detached, in the second loop the wagon carrying material 44, and in the third and final loop the wagons carrying materials 33, 22, and 11 are detached in that order, for a total of 33 loops.

Examples5

  1. Example 1

    Input
    5
    1 2 3 4 5
    1 3 4 2 5
    
    Expected output
    3
    
  2. Example 2

    Input
    2
    1 2
    1 2
    
    Expected output
    1
    
  3. Example 3

    Input
    2
    1 2
    2 1
    
    Expected output
    2
    
  4. Example 4

    Input
    5
    5 4 3 2 1
    1 2 3 4 5
    
    Expected output
    2
    
  5. Example 5

    Input
    3
    3 1 2
    2 3 1
    
    Expected output
    3