BZOJ2288 【POJ Challenge】生日礼物

题意:

给一个长度为\(n\)的数组,最多可以选\(m\)个连续段,问选取的最大值是多少

题解:

先把连续的符号相同的值合并,头和尾的负数去掉

然后如果正数的数量小于等于\(m\)的话,就直接输出正数的和

否则现在存在两种操作可以减少连续段数量

  1. 少选一个正数
  2. 选上两个正数之间的负数,把两边合并

显然不可能选相邻的一正一负

现在问题转化为选择\(k\)个不连续的数,使得其绝对值的和最小

然后就和这道题一样了:BZOJ1150 [CTSC2007]数据备份Backup

//#pragma GCC optimize("O3")
//#pragma comment(linker, "/STACK:1024000000,1024000000")
#include<bits/stdc++.h>
using namespace std;
function<void(void)> ____ = [](){ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);};
const int MAXN = 2e5+7; int n,m,l[MAXN],r[MAXN];
bool used[MAXN];
vector<int> A;
int sgn(int x){ return x > 0 ? 1 : -1; }
struct cmp{
bool operator () (const pair<int,int> x, const pair<int,int> y)const{
return abs(x.first) > abs(y.first);
}
};
int main(){
____();
cin >> n >> m;
for(int i = 1; i <= n; i++){
int x; cin >> x;
if(!x) continue;
if(A.empty()){
if(x<=0) continue;
A.push_back(x);
}
else{
if(sgn(x)==sgn(A.back())) A.back() += x;
else A.push_back(x);
}
}
if(!A.empty() and sgn(A.back())==-1) A.pop_back();
int cnt = 0, ret = 0;
for(int x : A) if(x>0) cnt++, ret += x;
if(cnt<=m){
cout << ret << endl;
return 0;
}
A.insert(A.begin(),-1);
priority_queue<pair<int,int>,vector<pair<int,int> >,cmp> que;
for(int i = 1; i < (int)A.size(); i++){
que.push(make_pair(A[i],i));
l[i] = i - 1; r[i] = i + 1;
}
r[A.size() - 1] = 0;
cnt -= m;
while(cnt--){
while(used[que.top().second]) que.pop();
auto p = que.top(); que.pop();
ret -= abs(p.first);
if(!l[p.second]) used[r[p.second]] = true, l[r[r[p.second]]] = 0;
else if(!r[p.second]) used[l[p.second]] = true, r[l[l[p.second]]] = 0;
else{
A.push_back(A[l[p.second]] + A[r[p.second]] + A[p.second]);
int now = A.size() - 1;
que.push(make_pair(A.back(),now));
used[l[p.second]] = used[r[p.second]] = true;
l[now] = l[l[p.second]]; r[now] = r[r[p.second]];
if(l[l[p.second]]) r[l[l[p.second]]] = now;
if(r[r[p.second]]) l[r[r[p.second]]] = now;
}
}
cout << ret << endl;
return 0;
}

最新文章

  1. Log4j的简要概述
  2. [JS10] 获取时间
  3. ios之点语法
  4. COJ 1006 树上操作
  5. 【转】如何删除一个repository(仓库)
  6. Android项目实战-云词典
  7. (五)CSS和JavaScript基础
  8. django celery的分布式异步之路(一) 起步
  9. linux信息收集
  10. less &amp;进行选择判断css的样式
  11. Windows 下Redis的部署 及key 过期事件
  12. oracle data type
  13. scheduleAtFixedRate 与 scheduleWithFixedDelay 的区别
  14. elastic-job详解(二):作业的调度
  15. 从面向对象的角度重新认识JS世界
  16. Python pip源处理
  17. vue.js 初级之一
  18. WEBserver 性能测试
  19. ROS知识(11)----同步两台机器时钟
  20. XML的一些点

热门文章

  1. log4net配置及使用
  2. ThreadX应用笔记:内核初始化和任务调度
  3. Laya 踩坑日记-人物模型穿模,模型显示不正常
  4. 【SpringBoot1.x】SpringBoot1.x 检索
  5. 在阿里云托管的k8s上使用nas做动态存储
  6. spring cloud config —— git配置管理
  7. 查看pod日志无法查看的解决方式
  8. JAVA编程中button按钮,actionlistener和mouseClicked区别
  9. 一文读懂 TKE 及 Kubernetes 访问权限控制
  10. 图解 ECDHE 密钥交换算法