Submission #1307175

#TimeUsernameProblemLanguageResultExecution timeMemory
1307175chithanhnguyenFeast (NOI19_feast)C++20
71 / 100
30 ms30564 KiB
#include <bits/stdc++.h>
using namespace std;

#define int long long
#define ull unsigned long long
#define ld long double
#define pii pair<int, int>
#define fi first
#define se second
#define __builtin_popcount __builtin_popcountll
#define all(x) (x).begin(), (x).end()
#define BIT(x, i) (((x) >> (i)) & 1)
#define MASK(x) ((1ll << (x)))

#define debug(a, l, r) for (int _i = (l); _i <= (r); ++_i) cout << (a)[_i] << ' '; cout << '\n';

const int MAXN = 2005;
const int INF  = 1e18 + 7;
int n, k, a[300005], pref[300005];
int dp[MAXN][MAXN];

signed main() {
    #ifdef NCTHANH
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
    #endif
    ios_base::sync_with_stdio(0);
    cin.tie(nullptr); cout.tie(nullptr);

    cin >> n >> k;

    int check = 0;
    for (int i = 1; i <= n; ++i) {
        cin >> a[i];
        if (a[i] < 0) ++check;
        pref[i] = pref[i - 1] + a[i]; 
    }

    if (check == 0) {
        cout << pref[n];
        return 0;
    }

    if (k == 1) {
        int pre = 0, res = 0;
        for (int i = 1; i <= n; ++i) {
            pre = min(pre, pref[i - 1]);
            res = max(res, pref[i] - pre);
        }

        cout << res;
        return 0;
    }

    if (check == 1) {
        int sum = 0;
        for (int i = 1; i <= n; ++i)
            if (a[i] >= 0) sum += a[i];
        cout << sum;
        return 0;
    }

    for (int j = 1; j <= k; ++j) {
        int mx = -INF;
        for (int i = 1; i <= n; ++i) {
            dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
            mx = max(mx, dp[i - 1][j - 1] - pref[i - 1]);
            dp[i][j] = max(dp[i][j], mx + pref[i]);
            // for (int pre = i; pre >= 1; --pre) {
            //     dp[i][j] = max(dp[i][j], dp[pre - 1][j - 1] + (pref[i] - pref[pre - 1]));
            // }
        }
    }

    cout << dp[n][k];

    return 0;
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...