Submission #833141

#TimeUsernameProblemLanguageResultExecution timeMemory
833141veehzFeast (NOI19_feast)C++17
71 / 100
255 ms262144 KiB
#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
typedef long double ld;
#define pb push_back

int main() {
  int n, k;
  cin >> n >> k;
  vector<ll> a(n);
  for (int i = 0; i < n; i++) cin >> a[i];

  // subtask 1 a_i > 0
  if (*min_element(a.begin(), a.end()) >= 0) {
    cout << accumulate(a.begin(), a.end(), 0LL) << endl;
    return 0;
  }

  // subtask 2 at most one a_i < 0
  if (count_if(a.begin(), a.end(), [](ll x) { return x < 0; }) <= 1) {
    int pos =
        find_if(a.begin(), a.end(), [](ll x) { return x < 0; }) - a.begin();
    ll mx = 0;
    mx = max(mx, accumulate(a.begin(), a.begin() + pos, 0LL));
    mx = max(mx, accumulate(a.begin() + pos + 1, a.end(), 0LL));
    mx = max(mx, accumulate(a.begin(), a.end(), 0LL));
    if (k >= 2) mx = max(mx, accumulate(a.begin(), a.end(), 0LL) - a[pos]);
    cout << mx << endl;
    return 0;
  }

  // subtask 3 K = 1, maximum subarray
  if (k == 1) {
    ll mx = 0, cur = 0;
    for (int i = 0; i < n; i++) {
      cur += a[i];
      mx = max(mx, cur);
      cur = max(cur, 0LL);
    }
    cout << mx << endl;
    return 0;
  }

  // dp[n][k][2] // dp[cur_index][how_many_left_excluding_cur][is_in_subarray]
  vector<vector<vector<ll>>> dp(n + 1,
                                vector<vector<ll>>(k + 1, vector<ll>(2)));

  dp[0][k - 1][1] = a[0];
  for (int i = 1; i < n; i++) {
    // dp[i][k][0] = 0
    for (int j = 0; j < k; j++) {
      dp[i][j][0] = max(dp[i - 1][j][0], dp[i - 1][j][1]);
      dp[i][j][1] = max(dp[i - 1][j + 1][0], dp[i - 1][j][1]) + a[i];
    }
  }

  ll mx = 0;
  for (int i = 0; i <= k; i++) {
    mx = max(mx, max(dp[n - 1][i][0], dp[n - 1][i][1]));
  }
  cout << mx << endl;
}
#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...