#include <bits/stdc++.h>
using namespace std;
struct trans {
int c, f, v;
trans(int _c, int _f, int _v) : c(_c), f(_f), v(_v) {}
};
void solve()
{
int n, m;
cin >> n;
vector<trans> a;
int cnt = 0;
for (int i = 0; i < n; i++) {
int c, f, v;
cin >> c >> f >> v;
cnt += c;
a.emplace_back(c, f, -v);
}
cin >> m;
for (int i = 0; i < m; i++) {
int c, f, v;
cin >> c >> f >> v;
a.emplace_back(-c, f, v);
}
sort(a.begin(), a.end(), [](const auto &x, const auto &y) {
if (x.f == y.f) return x.v < y.v;
return x.f > y.f;
});
const long long INF = 1e18 + 18;
vector<long long> dp(cnt + 1, -INF);
dp[0] = 0;
for (auto [c, f, v] : a) {
// cerr << c << ' '<< f << ' ' << v << '\n';
if (c > 0) {
for (int j = cnt; j >= 0; j--) {
if (j - c >= 0 && dp[j - c] != -INF) dp[j] = max(dp[j], dp[j - c] + v);
}
}
else {
for (int j = 0; j <= cnt; j++) {
if (j - c <= cnt && dp[j - c] != -INF) dp[j] = max(dp[j], dp[j - c] + v);
}
}
}
long long ans = 0;
for (int i = 0; i <= cnt; i++) {
ans = max(ans, dp[i]);
}
cout << ans << '\n';
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int t = 1;
//cin >> t;
while (t--) {
solve();
}
return 0;
}