15014 - Money's Neighbors   

Description

Money is a teacher at NTHU. During class, he likes to choose a student and ask the students sitting around that student to come to the front and answer some questions.

However, there are simply too many students in the classroom, and Money cannot remember who is sitting next to whom.

Please help him!

The classroom consists of N rows and M columns of seats. Each seat is occupied by exactly one student. The student sitting in row i, column j has student ID A[i][j]. All student IDs are distinct.

There are Q queries. In each query, Money chooses a student with ID x. For that student, find the students sitting directly above, below, to the left, and to the right.

The classroom has a circular seating arrangement:

  • If you move upward from the first row, you reach the last row.
  • If you move downward from the last row, you reach the first row.
  • If you move left from the first column, you reach the last column.
  • If you move right from the last column, you reach the first column.

When N = 2 or M = 2, the same student may appear in more than one direction. Each student must be printed only once.

For each query, print all distinct neighboring student IDs in increasing order.

Constraints

  • 2 <= N, M
  • N * M <= 20000
  • 1 <= Q <= 100000
  • 1 <= A[i][j] <= 1000000000
  • All student IDs are distinct.
  • Every queried student ID appears in the classroom.

Example

Consider the following seating arrangement:

10 25  7 18
 3 12 30  6
21  9 15 27

If Money chooses student 10:

  • Moving up wraps around to student 21.
  • Moving down reaches student 3.
  • Moving left wraps around to student 18.
  • Moving right reaches student 25.

After sorting, the answer is:

3 18 21 25

Input

The first line contains two integers:

N M
  • N: the number of rows in the classroom.
  • M: the number of columns in the classroom.

The next N lines each contain M integers. The value A[i][j] represents the student ID of the student sitting in row i, column j.

The next line contains one integer:

Q

where Q is the number of queries.

Each of the following Q lines contains one integer:

x

representing the student ID chosen by Money.

In short, the input is given in the following order:

N M
N rows of student IDs
Q
Q queried student IDs

Sample Input

3 4
10 25 7 18
3 12 30 6
21 9 15 27
4
10
12
27
30

Output

For each query, output all distinct student IDs sitting directly above, below, to the left, or to the right of student x.

Print the student IDs in increasing order. Separate adjacent IDs with one space.

If the same student appears in more than one direction, print that student only once.

Sample Output

3 18 21 25
3 6 9 25
6 15 18 21
6 7 12 15

Sample Input  Download

Sample Output  Download

Tags




Discuss