#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MAXN = 1000 * 1000 + 1;
const int MAXM = 1000 * 1000 + 1;
const int MAXN2 = 2000 + 1;
const int MAXM2 = 2000 + 1;
ll dp[MAXN2][MAXM2];
ll a[MAXN];
ll s[MAXN];
ll p[MAXN];
ll b[MAXM];
ll t[MAXM];
ll q[MAXM];
ll sprefa[MAXN];
ll sprefb[MAXM];
ll sprefp[MAXN];
ll sprefq[MAXM];
void rozw2 (int n, int m) {
    for (int i = 1; i <= n; i ++) {
        sprefa[i] = sprefa[i - 1] + a[i];
    }
    for (int i = 1; i <= m; i ++) {
        sprefb[i] = sprefb[i - 1] + b[i];
    }
    for (int i = 0; i <= n; i ++) {
        for (int j = 0; j <= m; j ++) {
            if (i > 0) {
                dp[i][j] = max(dp[i][j], dp[i - 1][j] + (sprefa[i] + sprefb[j] <= s[i]));
            }
            if (j > 0) {
                dp[i][j] = max(dp[i][j], dp[i][j - 1] + (sprefa[i] + sprefb[j] <= t[j]));
            }
        }
    }
    cout << dp[n][m] << "\n";
}
void rozw1 (int n, int m) {
    for (int i = 1; i <= n; i ++) {
        sprefa[i] = sprefa[i - 1] + a[i];
        sprefp[i] = sprefp[i - 1] + p[i];
    }
    for (int i = 1; i <= m; i ++) {
        sprefb[i] = sprefb[i - 1] + b[i];
        sprefq[i] = sprefq[i - 1] + q[i];
    }
    ll S = s[1];
    ll rekord = LLONG_MIN;
    for (int i = 0; i <= n; i ++) {
        if (sprefa[i] > S) {
            continue;
        }
        int pocz = 0, kon = m, wyn;
        while (pocz <= kon) {
            int sr = (pocz + kon)/ 2;
            if (sprefa[i] + sprefb[sr] <= S) {
                wyn = sr;
                pocz = sr + 1;
            } else {
                kon = sr - 1;
            }
        }
        rekord = max(rekord, sprefp[i] + sprefq[wyn]);
    }
    cout << rekord << "\n";
}
int main () {
    ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
    int n, m;
    cin >> n >> m;
    bool rowne1 = true;
    for (int i = 1; i <= n; i ++) {
        cin >> a[i] >> s[i] >> p[i];
        if (p[i] != 1LL) {
            rowne1 = false;
        }
    }
    for (int i = 1; i <= m; i ++) {
        cin >> b[i] >> t[i] >> q[i];
        if (q[i] != 1LL) {
            rowne1 = false;
        }
    }
    if (rowne1) {
        rozw2(n, m);
        return 0;
    }
    rozw1(n, m);
    return 0;
}
| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... |