Under construction

Still being built. Things may change

Count Values in a Sorted Matrix

Interview

Time limit15sMemory limit512 MB

Summary
Count entries in each query range [X, Y] inside a matrix whose rows and columns are sorted ascending.
Level

Medium5 of 10

Topics
Binary search, Matrix
Solved
No attempts yet

Problem

You are given a matrix AA of natural numbers whose rows and columns are all sorted in ascending order, so A[i][j]≥A[i−1][j]A[i][j] \ge A[i-1][j] and A[i][j]≥A[i][j−1]A[i][j] \ge A[i][j-1] hold for every ii and jj.

You are also given one or more integer pairs (X,Y)(X, Y) with Y≥XY \ge X. For each pair, count how many values of the matrix are greater than or equal to XX and smaller than or equal to YY.

Input

The first line has the number of rows NN and the number of columns MM. (1≤N,M≤100001 \le N, M \le 10000)

The next NN lines give the matrix values row by row, MM integers per line separated by spaces.

The query pairs (X,Y)(X, Y) follow the matrix. Each pair is two integers, and you keep reading until the input ends. There is at least one pair and at most 100 pairs, and no truncated pair is left at the end.

Every matrix value is a natural number, and those values together with XX and YY all fit in a signed 32-bit integer. X≤YX \le Y always holds. Spaces and line breaks may appear freely between the numbers.

Output

For each query pair, print how many matrix values are greater than or equal to XX and smaller than or equal to YY, one per line, in the order the pairs are given.

Examples1

  1. Example 1

    Input
    2 4
    1 5 10 10
    2 10 20 99
    
    10 99
    2 9
    100 1000
    10 10
    
    Expected output
    5
    2
    0
    3