http://www.lydsy.com/JudgeOnline/problem.php?id=2288
只会DP的蒟蒻飘过
和hzwer的对拍了下没问题,为什么DP会wa捏?
----------------------------------------------------------------------------------------------------
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<cstring>
#define inf 0x7fffffff
using namespace std;
struct heap{int v,x,av;}h[200010];
int n,m,a[100010];
int tmp,sz,ans,tot;
int v[100010],cnt;
int next[100010],pre[100010],pos[100010];
inline int read()
{
char ch=getchar();
int f=1,x=0;
while(!(ch>='0'&&ch<='9')){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+(ch-'0');ch=getchar();}
return x*f;
}
void pushup(int x)
{
while(h[x].av<h[x>>1].av)
{
pos[h[x>>1].x]=x;
swap(h[x],h[x>>1]);
x=x>>1;
}
pos[h[x].x]=x;
}
void push(int v,int x)
{
sz++;h[sz].v=v;h[sz].x=x;h[sz].av=abs(v);
pos[x]=sz;
pushup(sz);
}
void pushdown(int x)
{
int to;
while((x<<1)<=sz)
{
to=(x<<1);
if(to<sz && h[to].av>h[to+1].av)to++;
if(h[x].av>h[to].av)
{
pos[h[to].x]=x;
swap(h[to],h[x]);
x=to;
}
else break;
}
pos[h[x].x]=x;
}
void del(int x)
{
h[x].av=inf;
pushdown(x);
}
void init()
{
n=read();m=read();
for(int i=1;i<=n;i++)
{
a[++tmp]=read();
if(a[tmp]==0)tmp--;
}
v[++cnt]=a[1];
for(int i=2;i<=tmp;i++)
{
if((a[i]>0&&a[i-1]>0)||(a[i-1]<0&&a[i]<0))v[cnt]+=a[i];
else v[++cnt]=a[i];
}
for(int i=1;i<=cnt;i++)if(v[i]>0){ans+=v[i];tot++;}
for(int i=1;i<=cnt;i++){next[i]=i+1;pre[i]=i-1;}
pre[1]=-1;next[cnt]=-1;
}
void solve()
{
int a,b;heap k;
for(int i=1;i<=cnt;i++)push(v[i],i);
while(tot>m)
{
k=h[1];
if(pre[k.x]==-1)
{
if(k.v>0){ans-=k.v;del(1);}
else{del(1);tot++;}
pre[next[k.x]]=-1;
}
else if(next[k.x]==-1)
{
if(k.v>0){ans-=k.v;del(1);}
else{del(1);tot++;}
next[pre[k.x]]=-1;
}
else
{
ans-=k.av;
a=next[k.x];b=pre[k.x];
pre[k.x]=pre[b];next[pre[b]]=k.x;
next[k.x]=next[a];pre[next[a]]=k.x;
h[1].av=h[pos[a]].av+h[pos[b]].av-h[1].av;
h[1].v+=h[pos[a]].v+h[pos[b]].v;
pushdown(1);
del(pos[a]);del(pos[b]);
}
tot--;
}
printf("%d\n",ans);
}
int main()
{
init();
solve();
return 0;
}