2288: 【POJ Challenge】生日礼物
Time Limit: 10 Sec Memory Limit: 128 MB
Submit: 887 Solved: 271
[Submit][Status][Discuss]
Description
ftiasch 18岁生日的时候,lqp18_31给她看了一个神奇的序列 A1, A2, …, AN. 她被允许选择不超过 M 个连续的部分作为自己的生日礼物。
自然地,ftiasch想要知道选择元素之和的最大值。你能帮助她吗?
Input
第1行,两个整数 N (1 ≤ N ≤ 105) 和 M (0 ≤ M ≤ 105), 序列的长度和可以选择的部分。
第2行, N 个整数 A1, A2, …, AN (0 ≤ |Ai| ≤ 104), 序列。
Output
一个整数,最大的和。
Sample Input
5 2
2 -3 2 -1 2
Sample Output
5
HINT
Source
sol:
先把所有正数团和负数团弄出来,然后在这个新序列上做,考虑什么时候我们会取一个负数团,显然是因为我们段数不够了,取出一个负数团使得这个团左右两边的正数团被合并起来了。我们考虑一个贪心的做法,我们先把所有的正数团都给取出来,然后贪心的每次删掉最不优的,或是选出一个负数团,来达到使得选出的段-1的目的
我们考虑把这个团丢到一个堆里面,从这个堆中选出一个正数团,意味着这个正数团被我们删掉了,如果选出一个负数团,意味着我们把这个负数团给选了然后合并了两边的正数团。但是这样的话,选出了团i,那么团i-1和i+1就不能选了(我们必须选出连续的一段)。那么问题转化成了,选出若干个不相邻的数,使得他们的和最小。那么这题和bzoj1500数据备份一模一样,考虑使用一个链表来维护这个信息。
#include<cstdio>
#include<algorithm>
#include<string>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<iostream>
#include<queue>
using namespace std;
int n,m;
inline int read()
{
char c;
int res,flag=0;
while((c=getchar())>'9'||c<'0') if(c=='-')flag=1;
res=c-'0';
while((c=getchar())>='0'&&c<='9') res=(res<<3)+(res<<1)+c-'0';
return flag?-res:res;
}
const int N=110000;
int a[N],top;
bool pos;
struct cc
{
int val,id;
friend inline bool operator <(const cc &a,const cc &b)
{
return a.val>b.val;
}
};
priority_queue<cc> q;
const int inf=1e9;
int ans,pre[N],nex[N],len[N];
int main()
{
// freopen("2288.in","r",stdin);
// freopen("2288.out","w",stdout);
n=read();
m=read();
int i,tmp=0,x;
for(i=1;i<=n;++i)
{
x=read();
if(x>0)
{
tmp=x;
pos=1;
break;
}
}
for(i=i+1;i<=n;++i)
{
x=read();
if(x>0)
{
if(pos) tmp+=x;
else
{
a[++top]=tmp;
pos^=1;
tmp=x;
}
}
else
{
if(pos)
{
a[++top]=tmp;
pos^=1;
tmp=x;
}
else tmp+=x;
}
}
if(pos) a[++top]=tmp;
for(int i=1;i<=top;++i)
{
if(a[i]>0)
{
m--;
ans+=a[i];
}
pre[i]=i-1;
nex[i]=i+1;
len[i]=abs(a[i]);
q.push((cc){len[i],i});
}
pre[1]=0;
nex[top]=0;
if(m>=0)
{
printf("%d\n",ans);
return 0;
}
m=abs(m);
int l,r;
for(int i=1;i<=m;++i)
{
while(q.top().val!=len[q.top().id]) q.pop();
ans-=q.top().val;
x=q.top().id;
l=pre[x];r=nex[x];
if(l&&r)
pre[nex[pre[l]]=x]=pre[l];
nex[pre[nex[r]]=x]=nex[r];
len[x]=l&&r?len[l]+len[r]-len[x]:inf;
len[l]=inf;
len[r]=inf;
q.pop();
q.push((cc){len[x],x});
}
printf("%d",ans);
}