Count Values in a Sorted Matrix
InterviewTime limit15sMemory limit512 MB
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 of natural numbers whose rows and columns are all sorted in ascending order, so and hold for every and .
You are also given one or more integer pairs with . For each pair, count how many values of the matrix are greater than or equal to and smaller than or equal to .
Input
The first line has the number of rows and the number of columns . ()
The next lines give the matrix values row by row, integers per line separated by spaces.
The query pairs 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 and all fit in a signed 32-bit integer. 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 and smaller than or equal to , one per line, in the order the pairs are given.