/*#pragma GCC target ("avx2")
#pragma GCC optimize ("O3")
#pragma GCC optimize("Ofast")
#pragma GCC optimize ("unroll-loops")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")/**/
#include<bits/stdc++.h>
/**/
//typedef int ll;
typedef long long ll;
typedef unsigned long long ull;
typedef std::string str;
/*typedef __int128 vll;
typedef unsigned __int128 uvll;*/
#define llll std::pair<ll , ll>
#define pb push_back
#define pf push_front
#define halo cout << "hello\n"
#define fi first
#define sec second
#define all(a) a.begin() , a.end()
const ll limit = 1e15 + 7;
const ll ous = 1e5 + 7;
const ll dx[4] = {-1 , 0 , 1 , 0} , dy[4] = {0,1,0,-1};
ll n , m;std::vector<std::pair<llll , llll>> ar;
bool cmp(std::pair<llll , llll> a , std::pair<llll , llll> b){
if(a.fi.sec != b.fi.sec){
return a.fi.sec > b.fi.sec;
}
return a.sec.sec < b.sec.sec;
}
void solve(){
std::cin >> n;
ll tot = 0;
for(ll i = 0;n>i;i++){
ll x , y , z;std::cin >> x >> y >> z;
ar.pb({{x , y} , {z , -1}});
tot += x;
}
std::cin >> m;
for(ll i = 0;m>i;i++){
ll x , y , z;std::cin >> x >> y >> z;
ar.pb({{x , y} , {z , 1}});
}
std::sort(all(ar) , cmp);
std::vector<ll> dp(tot + 5 , -limit);
dp[0] = 0;
for(ll i = 0;ar.size()>i;i++){
if(ar[i].sec.sec == -1){
for(ll j = tot - ar[i].fi.fi;0<=j;j--){
dp[j + ar[i].fi.fi] = std::max(dp[j + ar[i].fi.fi] , dp[j] - ar[i].sec.fi);
}
}
else{
for(ll j = ar[i].fi.fi;tot>=j;j++){
dp[j - ar[i].fi.fi] = std::max(dp[j - ar[i].fi.fi] , dp[j] + ar[i].sec.fi);
}
}
}
ll mx = 0;
for(ll i =0;tot>=i;i++){
mx = std::max(dp[i] , mx);
}
std::cout << mx << "\n";
return;/**/
}
signed main(){
ll t=1;
//std::cin >> t;
ll o = 1;
while(t--){
//cout << "Case " << o++ << ":\n";
solve();
}
return 0;
}/**/