#include <bits/stdc++.h>

using namespace std;

int main()
{
    int n, m, q;
    cin >> n >> m;
    vector<vector<int>> grid;
    for(int i=0;i<n;i++){
        grid.push_back({});
        for(int j=0;j<m;j++){
            grid[i].push_back(0);
            cin >> grid[i][j];
        }
    }
    
    for(int i=0;i<n;i++){
        for(int j=0;j<m;j++){
            cout << grid[i][j] << " ";
        }
        cout << endl;
    }
    
    cin >> q;
    for(int a=0;a<q;a++){
        int x,y;
        cin >> x >> y;
        vector<int> cur(n, grid[0][0]);
        for(int i=0;i<n;i++){
            for(int j=0;j<m;j++){
                cout << cur[i] << " ";
            }
            cout << endl;
        }
        for (int i = 1; i < n; i++){
            cur[i] = cur[i - 1] + grid[i][0];
        }
        for (int j = 1; j < m; j++){
            cur[0] += grid[0][j]; 
            for (int i = 1; i < n; i++){
                cur[i] = min(cur[i - 1], cur[i]) + grid[i][j];
            }
        }
        cout << cur[n-1];
    }
    
    return 0;
    
}