#include <iostream>
#include <vector>

using namespace std;

vector<int> a, b, c, d;
vector<int> polja[3];

long long Case1(int n, int m)
{
    long long rez = 0;
    for (int i = 1; i <= m; i++)
    {
        polja[0].push_back(1);
        polja[1].push_back(i);
        polja[2].push_back(c[i]);
        b[1] -= c[i];
        rez += c[i];
    }
    for (int i = 1; b[1] > 0 && i <= m; i++)
    {
        int maks = min(b[1], d[i] - c[i]);
        polja[2][i-1] += maks;
        b[1] -= maks;
        rez += maks;
    }
    return rez;
}

long long Case2(int n, int m)
{
    long long rez = 0;
    for (int i = 1; i <= n; i++)
    {
        polja[0].push_back(i);
        polja[1].push_back(i);
        polja[2].push_back(b[i]);
        rez += b[i];
    }
    return rez;
}

long long Case3(int n, int m)
{
    long long rez = 0;
    int i = 1, j = 1;
    while ((i <= n || j <= m) && (i + j != n + m))
    {
        int maks = min(b[i], d[j]);
        polja[0].push_back(i);
        polja[1].push_back(j);
        polja[2].push_back(maks);
        b[i] -= maks;
        d[j] -= maks;
        rez += maks;
        if (b[i] == 0)
            i++;
        else
            j++;
    }
    return rez;
}

long long Slucaj(int n, int m)
{
    if (n == 1)
        return Case1(n, m);
    else if (n == m)
    {
        int count = 0;
        for (int i = 1; i <= n; i++)
            if (a[i] <= c[i] && c[i] <= b[i] && b[i] <= d[i])
                count++;
        if (count == n)
            return Case2(n, m);
    }
    else
    {
        int count = 0;
        for (int i = 1; i <= n; i++)
            if (a[i] == b[i])
                count++;
        for (int i = 1; i <= m; i++)
            if (c[i] == d[i])
                count++;
        if (count == n + m)
            return Case3(n, m);
    }
    return 0;
}

int main()
{
    int n, m;
    cin >> n >> m;
    a.push_back(0);
    b.push_back(0);
    c.push_back(0);
    d.push_back(0);
    for (int i = 0; i < n; i++)
    {
        int a1, b1;
        cin >> a1 >> b1;
        a.push_back(a1);
        b.push_back(b1);
    }
    for (int i = 0; i < m; i++)
    {
        int c1, d1;
        cin >> c1 >> d1;
        c.push_back(c1);
        d.push_back(d1);
    }
    cout << Slucaj(n, m) << endl;
    cout << polja[0].size() << endl;
    for (int i = 0; i < polja[0].size(); i++)
    {
        cout << polja[0][i] << " " << polja[1][i] << " " << polja[2][i] << endl;
    }
    return 0;
}