#include <iostream>
#include <cmath>


using namespace std;

bool test(int n,int m,int* matrix, int* a,int* b,int* c,int*d) {
    for (size_t i = 0; i < n; i++)
    {
        int zbir = 0;
        for (size_t j = 0; j < m; j++)
        {
            zbir += matrix[i, j];
        }
        if (zbir != b[i])
            return false;
    }
    for (size_t i = 0; i < n; i++)
    {
        int zbir = 0;
        for (size_t j = 0; j < m; j++)
        {
            zbir += matrix[j, i];
        }
        if (zbir != d[i])
            return false;
    }
    return true;
}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    int n, m;
    cin >> n >> m;
    int* mat = new int[n, m];
    int br = 0;
    int* a = new int[n];
    int* b = new int[n];
    int* c = new int[m];
    int* d = new int[m];
    for (size_t i = 0; i < n; i++)
    {
        cin >> a[i] >> b[i];
        br += b[i];
    }
    for (size_t j = 0; j < m; j++)
    {
        cin >> c[j] >> d[j];
    }
    for (size_t i = 0; i < n; i++)
    {
        for (size_t j = 0; j < m; j++)
        {
            mat[i, j] = min(a[i], c[j]);
        }
    }
    //bool next = test(n, m, mat, a, b, c, d);
    //cout << next << endl;
    for (size_t i = 0; i < n; i++)
    {
        
    }
    cout << br<<endl;
    for (size_t i = 0; i < n; i++)
    {
        for (size_t j = 0; j < m; j++)
        {
            cout << mat[i, j] << " ";
        }
        cout << endl;
    }
}