All problems

Problem 367

Relative Sort Array

Easy · 10 pts · Array, Hash Table, Sorting, Counting

Problem

You are given two arrays A and B. The elements of B are distinct, and every element of B also appears in A. Sort A so that its elements follow the order in which they appear in B: all copies of B[0] first, then all copies of B[1], and so on. Elements of A that do not appear in B go at the end in ascending order.

Input

First line: N. Second line: the N elements of A. Third line: M. Fourth line: the M distinct elements of B.

Output

Print the sorted array A, separated by spaces.

Constraints

1 <= N, M <= 1000; 0 <= value <= 1000

Example input

11
2 3 1 3 2 4 6 7 9 2 19
6
2 1 4 3 9 6

Example output

2 2 2 1 4 3 3 9 6 7 19

Explanation

B gives the order 2, 1, 4, 3, 9, 6. A's values follow it (2 2 2 1 4 3 3 9 6), and the leftover values 7 and 19 come last in ascending order.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Single Element in a Sorted Array Next: Sort Array by Increasing Frequency