This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
using namespace std;
const int N = 3e5 + 5;
vector<long long> arr (N);
vector<long long> comp;
vector< vector<long long> > g (N);
bool is_rem [N];
template<typename T>
struct Kadane {
long long best;
long long cur;
int s, start, end;
Kadane (vector<T> &a) {
best = cur = s = start = end = 0;
for (int i = 0; i < (int) a.size(); i++) {
cur += a[i];
if (cur < 0) {
cur = 0;
s = i + 1;
}
if (cur > best) {
best = cur;
start = s;
end = i + 1;
}
}
}
};
int main () {
ios::sync_with_stdio(0);
cin.tie(0);
int n, k;
cin >> n >> k;
for (int i = 0; i < n; i++) cin >> arr[i];
for (int i = 0; i < n; i++) {
if (comp.empty() || ( (arr[i] >= 0) ^ (comp.back() >= 0) ) == true ) {
comp.emplace_back(arr[i]);
continue;
}
long long cur = arr[i];
while (!comp.empty() && ( (arr[i] >= 0) ^ (comp.back() >= 0) ) == false ) {
cur += comp.back();
comp.pop_back();
}
comp.emplace_back(cur);
}
int tot = count_if (comp.begin(), comp.end(), [&] (int x) {
return (x > 0);
});
if (tot <= k) {
long long s = 0;
for (auto to : comp) s += (to >= 0 ? to : 0);
cout << s << '\n';
return 0;
}
int primeiro = -1;
int ultimo = -1;
for (int i = 0; i < (int) comp.size(); i++) {
if (comp[i] > 0) {
if (primeiro == -1) primeiro = i;
else ultimo = i + 1;
}
}
vector<long long> neg;
for (int i = primeiro; i < ultimo; i++) {
if (comp[i] < 0) {
neg.emplace_back(i);
}
}
sort (neg.begin(), neg.end(), [&] (int x, int y) {
return comp[x] < comp[y];
});
int blocos = 1;
for (auto to : neg) {
if (blocos < k) {
++blocos;
is_rem[to] = true;
}
}
int idx = 0;
for (int i = primeiro; i < ultimo; i++) {
if (is_rem[i]) {
++idx;
continue;
}
g[idx].emplace_back(comp[i]);
}
long long res = 0;
for (auto vec : g) {
if (!vec.empty()) {
Kadane <long long> solve (vec);
res += solve.best;
}
}
cout << res << '\n';
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... |