#include <bits/stdc++.h>
using namespace std;
long long mat[2010][2010];
long long dp[2010][2010];
long long n, m, q;
long long prefix1[500010];
long long prefix2[500010];
long long sufix1[500010];
long long sufix2[500010];
long long niz1[500010];
long long niz2[500010];
long long rez1[500010];
long long rez2[500010];
int main(){
	scanf("%lld %lld", &n, &m);
	if(n == 2){
		for(int i = 1; i <= m; i++){
			scanf("%lld", &niz1[i]);
			prefix1[i] = niz1[i] + prefix1[i - 1];
		}
		for(int i = 1; i <= m; i++){
			scanf("%lld", &niz2[i]);
			prefix2[i] = niz2[i] + prefix2[i - 1];
		}
		for(int i = m; i >= 1; i--)
			sufix2[i] = sufix2[i + 1] + niz2[i];
	}
	else{
		for(int i = 1; i <= n; i++){
			for(int j = 1; j <= m; j++){
				scanf("%lld", &mat[i][j]);
			}
		}
	}
	scanf("%lld", &q);
	if(n == 2){
		/*cout << "prefixi" << endl;
		for(int i = 1; i <= m; i++)
			cout << prefix1[i] << " ";
		cout << "sufixi" << endl;
		for(int i = 1; i <= m; i++)
			cout << sufix2[i] << " ";
		cout << endl << endl;*/
		// prvo racunaj kad je a = 2
		// tada moramo ici bar do polja b dok smo u prvom nizu
		rez2[m] = niz2[m] + prefix1[m];
		for(int i = m - 1; i >= 1; i--){
			rez2[i] = min(rez2[i + 1], prefix1[i] + sufix2[i]);
		}

		// racunaj kad je a = 1
		// tada moramo ici najdalje do polja b dok smo u prvom nizu
		rez1[1] = niz1[1] + sufix2[1];
		for(int i = 2; i <= m; i++){
			rez1[i] = min(rez1[i - 1], prefix1[i] + sufix2[i]);
		}

		while(q--){
			long long a, b;
			scanf("%lld %lld", &a, &b);
			if(a == 1)
				printf("%lld\n", rez1[b - 1]);
			if(a == 2)
				printf("%lld\n", rez2[b + 1]);
		}
		return 0;
	}
	while(q--){
		long long a, b;
		scanf("%lld %lld", &a, &b);
		dp[a][b] = 1e17;
		for(int i = 1; i <= n; i++){
			for(int j = 1; j <= m; j++){
				if(i == a && j == b)
					continue;
				if(i == 1 && j == 1)
					dp[i][j] = mat[i][j];
				else if(i > 1 && j == 1){
					if(dp[i - 1][j] == 1e17)
						dp[i][j] = 1e17;
					else
						dp[i][j] = mat[i][j] + dp[i - 1][j];
				}
				else if(i == 1 && j > 1)
					if(dp[i][j - 1] == 1e17)
						dp[i][j] = 1e17;
					else
						dp[i][j] = mat[i][j] + dp[i][j - 1];
				else
					dp[i][j] = mat[i][j] + min(dp[i - 1][j], dp[i][j - 1]);
			}
		}
		printf("%lld\n", dp[n][m]);
	}
	return 0;
}