Permutations (Codeforces 189C)
Tags: Implement, greedy

Happy PMP is freshman and he is learning about algorithmic problems. He enjoys playing algorithmic games a lot.One of the seniors gave Happy PMP a nice game. He is given two permutations of numbers 1 through n and is asked to convert the first one to the second. In one move he can remove the last number from the permutation of numbers and inserts it back in an arbitrary position. He can either insert last number between any two consecutive numbers, or he can place it at the beginning of the permutation.Happy PMP has an algorithm that solves the problem. But it is not fast enough. He wants to know the minimum number of moves to convert the first permutation to the second. 

Input: The first line contains a single integer n (1 ≤ n ≤ 2·105) — the quantity of the numbers in the both given permutations. Next line contains n space-separated integers — the first permutation. Each number between 1 to n will appear in the permutation exactly once. Next line describe the second permutation in the same format.

Output: Print a single integer denoting the minimum number of moves required to convert the first permutation to the second.

Note: In the first sample, he removes number 1 from end of the list and places it at the beginning. After that he takes number 2 and places it between 1 and 3.In the second sample, he removes number 5 and inserts it after 1.In the third sample, the sequence of changes are like this:  1 5 2 3 4 1 4 5 2 3 1 3 4 5 2 1 2 3 4 5  So he needs three moves.

Sample Inputs:
3
3 2 1
1 2 3

5
1 2 3 4 5
1 5 2 3 4

5
1 5 2 3 4
1 2 3 4 5

Sample Outputs:
2

1

3

Solution (Python):
n = int(input())
p1 = list(map(int, input().split()))
p2 = list(map(int, input().split()))
count = 0
for i in range(n):
    if p2[i] == p1[count]:
        count += 1
print(n - count)

Solution (Python):
def solve():
    n = int(input())
    p1 = list(map(int, input().split()))
    p2 = list(map(int, input().split()))
    p2_idx = {}
    p1_idx = []
    for (i, num) in enumerate(p2):
        p2_idx[num] = i
    for p in p1:
        p1_idx.append(p2_idx[p])
    for i in range(1, n):
        if p1_idx[i] < p1_idx[i - 1]:
            print(n - i)
            return
    print(0)
solve()

Solution (Python):
def solve():
    n = int(input())
    p1 = list(map(int, input().split()))
    p2 = list(map(int, input().split()))
    p2_idx = {}
    p1_sort = []
    for (i, num) in enumerate(p2):
        p2_idx[num] = i
    for p in p1:
        p1_sort.append(p2_idx[p])
    prev = p1_sort[0]
    for (ix, px) in enumerate(p1_sort[1:]):
        if px < prev:
            print(n - ix - 1)
            return
        prev = px
    print(0)
solve()