Count Values in a Sorted Matrix

No attempts yetTime limit15sMemory limit512 MB

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[i1][j]A[i][j] \ge A[i-1][j] and A[i][j]A[i][j1]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 YXY \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. (1N,M100001 \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. XYX \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.