#include <bits/stdc++.h>

using namespace std;

long long minPathSum (vector<vector<long long>> grid, long long sum, long long x, long long y) {
    long int n, m;
    n = grid.size(),
    m = grid[0].size();
    grid[x][y] = sum;
    for (long long i=0;i<n;i++){
        for(long long j=0;j<m;j++) {
            if(i==0 && j>0) grid[i][j] += grid[i][j-1];
            
            if(j==0 && i>0) grid[i][j] += grid[i-1][j];
            
            if(i>0 && j>0) grid[i][j] += min(grid[i][j-1], grid[i-1][j]);
        }
    }
    return grid[n-1][m-1];
};

int main()
{
    long int n, m;
    long long q, sum=0;
    cin >> n >> m;
    vector<vector<long long>> grid;
    for(long long i=0;i<n;i++){
        grid.push_back({});
        for(long long j=0;j<m;j++){
            grid[i].push_back(0);
            cin >> grid[i][j];
            sum += grid[i][j];
        }
    }
    
    cin >> q;
    for(long long i=0;i<q;i++){
        long long x, y;
        cin >> x >> y;
        cout << minPathSum(grid, sum, x-1, y-1);
    }

    return 0;
}