#include <bits/stdc++.h>
#define ll long long
#define MAXN 50010
using namespace std;
ll a[MAXN],b[MAXN],c[MAXN],d[MAXN];
vector<pair<ll,ll> > s;
map<pair<ll,ll>,ll> val;
int main()
{
    ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
    ll n,m,sum=0;
    cin >> n >> m;
    for (ll i=1;i<=n;i++)
        cin >> a[i] >> b[i];
    for (ll i=1;i<=m;i++)
        cin >> c[i] >> d[i];
    ll t=1;
    for (ll i=1;i<=n;i++)
    {
        while (true)
        {
            if (t>m || !a[i])
                break;
            if (d[t]==0)
            {
                while (d[t]==0 && t<=m)
                    t++;
                continue;
            }
            ll minn=min(a[i],d[t]);
            a[i]-=minn;
            b[i]-=minn;
            c[t]=max(0ll,c[t]-minn);
            d[t]-=minn;
            sum+=minn;
            if (!val[{i,t}])
                s.push_back({i,t});
            val[{i,t}]+=minn;
        }
    }
    t=1;
    for (ll i=1;i<=m;i++)
    {
        while (true)
        {
            if (t>n || !c[i])
                break;
            if (b[t]==0)
            {
                while (b[t]==0 && t<=n)
                    t++;
                continue;
            }
            ll minn=min(c[i],b[t]);
            c[i]-=minn;
            d[i]-=minn;
            b[t]-=minn;
            sum+=minn;
            if (!val[{t,i}])
                s.push_back({t,i});
            val[{t,i}]+=minn;
        }
    }
    t=1;
    for (ll i=1;i<=m;i++)
    {
        while (true)
        {
            if (t>n || !d[i])
                break;
            if (b[t]==0)
            {
                while (b[t]==0 && t<=n)
                    t++;
                continue;
            }
            ll minn=min(d[i],b[t]);
            d[i]-=minn;
            b[t]-=minn;
            sum+=minn;
            if (!val[{t,i}])
                s.push_back({t,i});
            val[{t,i}]+=minn;
        }
    }
    t=1;
    for (ll i=1;i<=n;i++)
    {
        while (true)
        {
            if (t>m || !b[i])
                break;
            if (d[t]==0)
            {
                while (d[t]==0 && t<=m)
                    t++;
                continue;
            }
            ll minn=min(b[i],d[t]);
            b[i]-=minn;
            d[t]-=minn;
            sum+=minn;
            if (!val[{i,t}])
                s.push_back({i,t});
            val[{i,t}]+=minn;
        }
    }
    cout << sum << "\n" << s.size() << "\n";
    for (auto it : s)
    {
        cout << it.first << " " << it.second << " " << val[it] << "\n";
    }
    return 0;
}