Rectangles and Queries

Given an N by N matrix with values at most 10, answer many rectangle queries, each asking how many distinct integers appear inside the submatrix.

Medium5Prefix sumMatrixImplementationBrute forceInterviewNo attempts yetTime limit2sMemory limit512 MB

Problem

You are given a square matrix AA with NN rows and NN columns. Write a program that answers queries about it.

  • x1 y1 x2 y2: print the number of distinct integers inside the submatrix whose top left cell is (x1,y1)(x_1, y_1) and whose bottom right cell is (x2,y2)(x_2, y_2).

Input

The first line contains NN (1N3001 \le N \le 300). Each of the next NN lines contains one row of the matrix as NN numbers. Rows are numbered from top to bottom and columns from left to right, both starting at 1. Every entry of the matrix is a natural number not greater than 10.

The next line contains QQ (1Q1000001 \le Q \le 100\,000). Each of the next QQ lines contains one query given as x1x_1, y1y_1, x2x_2, y2y_2, where xx is a row number and yy is a column number. (1x1x2N1 \le x_1 \le x_2 \le N, 1y1y2N1 \le y_1 \le y_2 \le N)

Output

For each query, print the answer on its own line.