eolymp
bolt
Try our new interface for solving problems

Maze

One of the most popular games of all times is the "Maze". The game is played on a \textbf{N}×\textbf{M} table. The player can make the instructions: 'left', 'right', 'up', 'down'. For each cell of the table and each instruction the game-master has defined the destination cell that the player moves to; that is, the player is given the map of the maze. Once a game was interrupted, and the master has forgotten which cell the player was in. Fortunately, a full record of the gameplay has remained, which is the sequence of the instructions made by the player. You are to write a program determining the cells that the player can be currently in. \InputFile The first line of the input contains two numbers \textbf{N} and \textbf{M} (\textbf{1} ≤ \textbf{N}, \textbf{M} ≤ \textbf{100}). Four blocks of N lines each follow. Each line contains \textbf{M} pairs, being the new coordinates of the player after making \textbf{k}'th instruction standing in the cell \textbf{(j, i)}, where \textbf{i} is the number of pair in the line, \textbf{j} is the number of line in the block, and \textbf{k} is the number of block. Following is the number \textbf{S} (\textbf{1} ≤ \textbf{S} ≤ \textbf{4000}) of the instructions made by the player. The last line contains the \textbf{S} numbers of the instructions made. \OutputFile The first line of the output must contain the number \textbf{L} of the cells that player can be in after making the given sequence of instructions. Each of the next \textbf{L} lines must contain the coordinates of these cells, ordered first by the first coordinate, and then by the second.
Time limit 0.5 seconds
Memory limit 64 MiB
Input example #1
2 3
1 2  1 3  1 3  
2 2  2 3  2 3  
2 1  2 2  2 3  
2 1  2 2  2 3  
1 1  1 1  1 2  
2 1  2 1  2 2  
1 1  1 2  1 3  
1 1  1 2  1 3  
4
1 2 3 4 
Output example #1
2
1 1
1 2
Author Andrew Khalyavin
Source Petrozavodsk summer training camp, August 2005