problems / 290

Hiking the Skyline

easy prefix-sums matrix arrays 1000 ms · 256 MB

Hiking the Skyline

A mountain trail is drawn as a side view: a picture of H rows and W columns. The characters are

  • #: rock,
  • .: open air.

Every column is a solid stack of rock resting on the bottom row, with only air above it. The height of a column is the number of # in it; a column with no rock at all has height 0.

A hiker stands on top of column l and walks to column r, one column at a time (to the right if l < r, to the left if l > r). Each step goes from one column to its neighbour: if the neighbour is higher by d, the hiker climbs d metres; if it is lower by d, the hiker descends d metres. The hiker never leaves the picture.

For each of q walks, report the total number of metres climbed and the total number of metres descended.

Input

The first line contains two integers H and W (1 ≤ H ≤ 1000, 1 ≤ W ≤ 10^5, H·W ≤ 2·10^6).

Each of the next H lines contains exactly W characters, each # or ., from the top row of the picture to the bottom row. In every column, all # cells are below all . cells.

The next line contains an integer q (1 ≤ q ≤ 2·10^5). Each of the next q lines contains two integers l and r (1 ≤ l, r ≤ W): a walk from column l to column r. Columns are numbered 1 to W from left to right, and l may equal r.

Output

For each walk, print one line with two integers: the total climb and the total descent, in metres.

Notes

In the first example the column heights are 1, 2, 1, 3, 2, 0, 1. The walk from column 2 to column 6 goes through heights 2, 1, 3, 2, 0: it climbs 2 metres (1 → 3) and descends 1 + 1 + 2 = 4 metres. The walk from column 6 back to column 2 passes the same columns in the opposite order, so the climbs and descents trade places: 4 metres up and 2 down. A walk that starts and ends on the same column climbs and descends nothing.

In the second example, columns 2 and 4 are empty and have height 0.

Example 1

Input

4 7
.......
...#...
.#.##..
#####.#
6
1 7
2 6
6 2
4 4
1 4
5 7

Output

4 4
2 4
4 2
0 0
3 1
1 2

Example 2

Input

3 5
.....
#...#
#.#.#
4
1 5
5 3
2 4
3 3

Output

3 3
1 2
1 1
0 0

Hints · reveal one at a time if you're stuck

Hint 1

First turn the picture into one height per column. Then notice that a walk to the left uses the same steps as the walk to the right over the same columns, just backwards: what happens to its climbs and descents?

Hint 2

Walking each query step by step can take 10^5 steps per walk, too slow for 2·10^5 walks. Precompute, for every column i, the total climb and the total descent from column 1 to column i; any rightward walk is then the difference of two of these: a prefix sum.

report an issue Prefer your own editor? sooks prep 290 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.