This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#pragma GCC optimize("O2")
#pragma GCC target("avx,avx2,fma")
#include <bits/stdc++.h>
#define FOR(i, a, b) for (int i = (a); i <= (b); i++)
#define FOD(i, a, b) for (int i = (a); i >= (b); i--)
#define REP(i, n) for (int i = 0; i < (n); i++)
#define ALL(x) (x).begin(), (x).end()
#define TIME (1.0 * clock() / CLOCKS_PER_SEC)
#define file(name) if (fopen(name".inp", "r")) { freopen(name".inp", "r", stdin); freopen(name".out", "w", stdout); }
using namespace std;
#define ii pair <long long, int>
#define fi first
#define se second
const int MAXN = 3e5 + 5;
const long long INF = 1e18 + 7;
int N, K, M = 0, L[MAXN], R[MAXN];
long long a[MAXN];
void solve(void) {
cin >> N >> K;
FOR(i, 1, N) {
int x; cin >> x;
if (M == 0) {if (x > 0) a[++M] = x; continue;}
if ((a[M] > 0) == (x > 0)) a[M] += x;
else a[++M] = x;
}
while (a[M] <= 0) M--;
int num_positive = 0;
N = M; set <ii> s;
FOR(i, 1, N) {
num_positive += a[i] > 0;
L[i] = i - 1; R[i] = i + 1;
s.insert(ii(abs(a[i]), i));
}
while (num_positive > K) {
int id = (*s.begin()).se; s.erase(s.begin());
long long val = a[id]; int l = L[id], r = R[id];
if (a[id] > 0) num_positive--;
if (l) {
if (L[l]) R[L[l]] = id;
s.erase(ii(abs(a[l]), l));
val += a[l];
num_positive -= a[l] > 0;
}
if (r) {
if (R[r]) L[R[r]] = id;
s.erase(ii(abs(a[r]), r));
val += a[r];
num_positive -= a[r] > 0;
}
a[id] = val;
L[id] = L[l]; R[id] = R[r];
if (L[id] == 0 && a[id] < 0) L[R[id]] = a[id] = 0;
else if (R[id] == 0 && a[id] < 0) R[L[id]] = a[id] = 0;
else s.insert(ii(abs(a[id]), id));
num_positive += a[id] > 0;
}
long long ans = 0;
for (auto x : s) ans += max(0ll, a[x.se]);
cout << ans;
}
signed main(void) {
ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);
//file("TASK");
//int T; cin >> T; while (T--)
solve();
cerr << "Time elapsed: " << TIME << " s.\n";
return (0 ^ 0);
}
/*
6 2
1 2 3 -10 5 6
*/
# | 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... |