#include <iostream>

using namespace std;

int main()
{
    long unsigned int M, N, S, Smax = 0, S1 = 0;
    cin >> N >> M;
    long unsigned int matrica[N][M];
    for(long unsigned int i = 0; i < N; i++)
    {
        for(long unsigned int j = 0; j < M; j++)
        {
            cin >> matrica[i][j];
        }
    }
    long unsigned int Q;
    cin >> Q;
    long unsigned int x[Q];
    long unsigned int y[Q];
    for(long unsigned int q = 0; q < Q; q++)
    {
        cin >> x[q] >> y[q];
    }
    if(N == 2)
    {
        for(long unsigned int q = 0; q < Q; q++)
        {
            if(y[q] == 1)
            {
                for(long unsigned int i = 1, j = x[q] - 1; j < M; j++)
                {
                    S1 = S1 + matrica[i][j];
                }
                for(unsigned int t = 0; t < x[q]; t++)
                {
                    S = 0;
                    for(unsigned int i=0; i < N; i++)
                    {
                        for(unsigned int j = 0; j < t;j++)
                        {
                            S = S + matrica[i][j];
                        }
                    }
                    if(S > Smax)
                    {
                        Smax = S;
                    }
                }
            }
            else if(y[q] == 2)
            {
                for(long unsigned int i = 0, j = 0; j < x[q] - 1; j++)
                {
                    S1 = S1 + matrica[i][j];
                }
                for(unsigned int i = 0; i < N; i++)
                {
                    for(unsigned int j = 0; j < x[q]; j++)
                    {
                        S1 = S1 + matrica[i][j];
                    }
                }
                for(unsigned int t = 0; t < M - x[q]; t++)
                {
                    S = 0;
                    for(unsigned int i = 0; i < N; i++)
                    {
                        for(unsigned int j = t; j < M; j++)
                        {
                            S = S + matrica[i][j];
                        }
                    }
                    if(S > Smax)
                    {
                        Smax = S;
                    }
                }
            }
            cout << Smax + S1 << endl;
        }
    }
    
}