problems / 260

Paged Metrics Table

easy binary-search matrix arrays 1000 ms · 256 MB

Paged Metrics Table

A metrics store records sample timestamps (in microseconds) and keeps them in pages. The pages form a table of R rows and C columns: each row is sorted in increasing order, and every row starts with a timestamp greater than the last timestamp of the row above it. All timestamps are distinct.

A dashboard sends q lookups. For each timestamp x, report the row and column of the cell holding x, or say that x is not stored.

Input

The first line contains two integers R and C (1 ≤ R, C and R·C ≤ 10^6).

Each of the next R lines contains C integers, the timestamps of one row (0 ≤ t ≤ 10^12). Each row is strictly increasing, and the first value of each row is greater than the last value of the previous row.

The next line contains q (1 ≤ q ≤ 2·10^5). Each of the next q lines contains one lookup x (0 ≤ x ≤ 10^12).

Timestamps can exceed 2^31, so use 64-bit integers.

Output

For each lookup, print one line: the row and the column of the cell holding x (both 1-based, separated by a space), or -1 if x is not in the table.

Notes

In the first example, 21 is in row 2, column 3. The value 13 falls between the end of row 1 and the start of row 2, and 60 is past the last cell, so both print -1.

In the second example the table has a single column, and some timestamps don't fit in a 32-bit integer.

Example 1

Input

3 4
2 5 9 12
15 20 21 30
31 40 45 50
5
21
2
50
13
60

Output

2 3
1 1
3 4
-1
-1

Example 2

Input

4 1
7
300
5000000000
999999999999
4
5000000000
7
8
999999999999

Output

3 1
1 1
-1
4 1

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

Hint 1

Read the table row by row, left to right. What do you notice about the sequence of timestamps you get? Also check the limits: scanning the table for every lookup is far too slow.

Hint 2

The whole table is one sorted sequence of R·C values, so each lookup is a binary search over it. Work out how a position in that sequence maps back to a row and column. If you search for the row first instead, be careful which row x can actually be in.

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

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