ch 1812 链表加优先队列

本文深入探讨了一种解决特定数组问题的算法思路,通过将数组分割为多个子数组,寻找能够达到最大和的子数组组合,同时考虑到负数元素的影响。文章详细解释了如何通过合并负数子数组两侧的正数子数组来优化解决方案,以满足限定的子数组数量要求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

思路:
先把数据分成最长的连续小块,满足每个小块里面要么只有负数,要么只有整数,那么最大的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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值