#include <stdio.h>
int min(int a, int b)
{
    if (a<b)
    {
        return a;
    }
    else
    {
        return b;
    }
}
int main() {
    int rows, columns, a, b;
    scanf("%d%d", &rows, &columns);
    int matrix[rows][columns];
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < columns; j++) {
            scanf("%d", &matrix[i][j]);
        }
    }
    int cases;
    scanf("%d", &cases);
    for (int c = 0; c < cases; c++) {
        int row, column;
        scanf("%d%d", &row, &column);

        int sum = 0;
        for (int a = 0; a <= row; a++) {
            for (int b = 0; b <= column; b++) {
                sum += matrix[a][b];
            }
        }
        int i=0;
        int j=0;
        while (i!=a && j!=b)
        {
            if (i*(j+1)==a*b || (i+1)*j!=a*b)
                a=a+min((i+1)*j, (j+1)*i);
            else
            {
                a=a+i*(j+1)+(i+1)*j-a*b;
            }
        }
        a=a+rows*columns;
        printf("%d", a);
    }

    return 0;
}