Under construction

Still being built. Things may change

Algorithm Class - Insertion Sort 3

Interview

Time limit1sMemory limit512 MB

Summary
Simulate insertion sort on array A and print 1 if the array ever equals B during the process, otherwise 0.
Level

Medium5 of 10

Topics
Simulation, Implementation, Sorting, Array
Solved
No attempts yet

Problem

Seojun is again working as a teaching assistant for the insertion sort class. Let us check through a problem whether the students understood what his father taught in class.

There is an array A holding N distinct positive integers. When array A is sorted in ascending order with insertion sort, check whether array A ever equals array B during the sorting process. The initial state of array A also counts as a state that can occur during sorting.

The pseudocode for insertion sort on an array of size N is as follows.

insertion_sort(A[1..N]) { # sorts A[1..N] in ascending order
    for i <- 2 to N {
        loc = i - 1;
        newItem = A[i];

        # at this point A[1..i-1] is already sorted
        while (1 <= loc and newItem < A[loc]) {
            A[loc + 1] <- A[loc];
            loc--;
        }
        if (loc + 1 != i) then A[loc + 1] = newItem;
    }
}

Input

The first line gives the size N of arrays A and B (5 ≤ N ≤ 10,000).

The next line gives the elements of array A, A1, A2, ..., AN, which are distinct. (1 ≤ Ai ≤ 109)

The next line gives the elements of array B, B1, B2, ..., BN. (1 ≤ Bi ≤ 109)

Output

Print 1 if array A equals array B at some point while insertion sort sorts array A in ascending order, and 0 otherwise.

Examples2

  1. Example 1

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

    Input
    5
    4 5 1 3 2
    1 3 2 4 5
    
    Expected output
    0