思路:
先把数据分成最长的连续小块,满足每个小块里面要么只有负数,要么只有整数,那么最大的ans就是每个正数小块的和。但是题目上规定了小块的数量,所以你需要将某些小块合成成一个小块,怎么合成呢?
就是每次把负数小块里面值最大的找到,然后把它和它左右两个正数小块合成,这样两个整数小块就变成了一个小块(中间有一个负数)。
这个我没做出来,抄的书上的代码
代码
#include <cstdio>
#include <iostream>
#include <iomanip>
#include <string>
#include <cstdlib>
#include <cstring>
#include <queue>
#include <set>
#include <vector>
#include <map>
#include <algorithm>
#include <cmath>
#include <stack>
#define INF 0x3f3f3f3f
#define IMAX 2147483646
#define LINF 0x3f3f3f3f3f3f3f3f
#define ll long long
#define ull unsigned long long
#define uint unsigned int
using namespace std;
const int N = 100006;
int n, m, a[N], s[N], nxt[N], prv[N];
bool v[N];
struct P {
int p, c;
bool operator < (const P x) const {
return abs((double)c) > abs((double)x.c);
}
};
priority_queue<P> q;
void Delete(int x) {
v[x] = 0;
prv[nxt[x]] = prv[x];
nxt[prv[x]] = nxt[x];
}
int main() {
cin >> n >> m;
for (int i = 1; i <= n; i++)
scanf("%d", &a[i]);
int tot = 1;
for (int i = 1; i <= n; i++)
if ((ll)s[tot] * a[i] >= 0) s[tot] += a[i];
else s[++tot] = a[i];
int ans = 0, cnt = 0;
for (int i = 1; i <= tot; i++) {
P p;
p.c = s[i];
p.p = i;
q.push(p);
if (s[i] > 0) {
ans += s[i];
cnt++;
}
prv[i] = i - 1;
nxt[i] = i + 1;
}
memset(v, 1, sizeof(v));
while (cnt > m) {
cnt--;
P p = q.top();
while (!v[p.p]) {
q.pop();
p = q.top();
}
q.pop();
if (prv[p.p] && nxt[p.p] != tot + 1) ans -= abs((double)s[p.p]);
else if (s[p.p] > 0) ans -= s[p.p];
else {
cnt++;
continue;
}
s[p.p] += s[prv[p.p]] + s[nxt[p.p]];
Delete(prv[p.p]);
Delete(nxt[p.p]);
p.c = s[p.p];
q.push(p);
}
cout << ans << endl;
return 0;
}