## COCI '14 Contest 5 #5 Jabuke

View as PDF

Points: 15 (partial)
Time limit: 1.0s
Memory limit: 128M

Problem type

It is often heard that the apple doesn't fall far from the tree. But is that really so?

The National Statistics Department has tracked the falling of apples in a fruit garden for consecutive years. The fruit garden can be represented as a matrix with dimensions . Each field of the matrix can contain more than one apple tree.

Interestingly enough, each year there was exactly one apple fall, so the Department decided to write down pairs of numbers that denote the row and column of the location where the apple fell during the year. Moreover, by next year, a new tree grew at that location.

Your task is to determine the squared distance between the nearest tree and the apple that fell, measured in unit fields of the matrix (we assume it is that tree from which the apple fell).

The distance between fields and in the matrix are calculated as:

#### Input

The first line of input contains two integers, and , the number of rows and columns of the matrix.

Each of the following lines contains characters x or .. The character . denotes an empty field, and the character x denotes a field with at least one tree.

The fruit garden will initially contain at least one tree.

After that, an integer follows, the number of years the fruit garden has been under observation.

Each of the following lines describes the falls of the apples. Each line contains a pair of integers that denote the row and column of the location where the apple fell in the year.

#### Output

Output numbers, the required squared distances from the task, each in its own line.

#### Scoring

In test cases worth 30% of total points, it will hold .

#### Sample Input 1

3 3
x..
...
...
3
1 3
1 1
3 2

#### Sample Output 1

4
0
5

#### Explanation for Sample Output 1

The closest apple to the one that fell in the first year is the apple in the field . The apple that fell in the second year fell on the exact field where the tree is located, so the squared distance is . The apple that fell in the third year is equally distant to all three existing trees in the fruit garden.

#### Sample Input 2

5 5
..x..
....x
.....
.....
.....
4
3 1
5 3
4 5
3 5

#### Sample Output 2

8
8
4
1