using System;
using System.Collections.Generic;
namespace takmicenjeKvalifikacije
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string[] sr = Console.ReadLine().Split();
            int n = int.Parse(sr[0]);
            int m = int.Parse(sr[1]);

            int[,] a = new int[n, m];
            for (int i = 0; i < n; i++)
            {
                string[] r = Console.ReadLine().Split();
                for (int j = 0; j < m; j++)
                {
                    a[i, j] = int.Parse(r[j]);
                }
            }

            int[,] min = new int[n, m];

            sr = Console.ReadLine().Split();
            int q = int.Parse(sr[0]);

            min[0, 0] = a[0, 0];

            for (int j = 1; j < m; j++)
            {
                min[0, j] = min[0, j - 1] + min[0, j];
            }

            for (int i = 1; i < n; i++)
            {
                min[i, 0] = min[i - 1, 0] + min[i, 0];
            }
            int[,] g = new int[q,q];
            for (int i = 0; i < q; i++)
            {
                sr = Console.ReadLine().Split();
                int x = int.Parse(sr[0]);
                int y = int.Parse(sr[1]);
                g[i, 0] = x;
                g[i, 1] = y;
            }

            for (int i = 0; i < q; i++)
            {
                min[g[i,0], g[i,1]] = int.MaxValue;

                for (int k = 1; i < n; i++)
                {
                    for (int j = 1; j < m; j++)
                    {
                        min[k, j] += Math.Min(min[k - 1, j], min[k, j - 1]) + a[k, j];
                        Console.Write(min[k, j] + " ");
                    }
                    Console.WriteLine();
                }
                min[g[i, 0], g[i, 1]] = a[g[i, 0], g[i, 1]];
                Console.WriteLine(min[n - 1, m - 1]);
            }

        }
    }w
}