2288双倍经验
。。发现我并没写2288的博客……太久远了
大概就是把相邻同符号的合起来
然后先把所有正的选上
如果大于m段的话就要调整一下
每次选择绝对值最小的一段和左右两段合并,然后如果是负的相当于把这段也选了,如果是正的相当于不选
数组开大点,开longlong
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<iomanip>
#include<cmath>
#include<cstring>
#include<ctime>
#include<vector>
#include<stack>
#include<queue>
#include<set>
#include<bitset>
#include<map>
using namespace std;
#define MAXN 1000010
#define MAXM 10010
#define INF 1000000000
#define MOD 1000000007
#define ll long long
#define eps 1e-8
struct gift{
ll av;
ll p;
gift(){
}
gift(ll x,ll y){
av=x;
p=y;
}
friend bool operator <(gift x,gift y){
return x.av!=y.av?x.av<y.av:x.p<y.p;
}
};
set<gift>s;
ll fro[MAXN],nxt[MAXN];
ll a[MAXN];
ll n,m,now,tot;
ll ans;
int main(){
ll i;
scanf("%lld%lld",&n,&m);
for(i=1;i<=n;i++){
scanf("%lld",&a[i]);
if(a[i]==0){
a[i]=a[i-1];
continue ;
}
if(a[i]<0==a[i-1]<0&&i!=1){
//cout<<"!";
a[tot]+=a[i];
}else{
//cout<<"@";
a[++tot]=a[i];
}
}
n=tot;
for(i=1;i<=n;i++){
fro[i]=i-1;
nxt[i]=i+1;
if(a[i]>0){
now++;
ans+=a[i];
//cout<<a[i]<<' '<<i<<endl;
}
s.insert(gift(abs(a[i]),i));
}
nxt[n]=0;
//cout<<n<<endl;
while(now>m){
gift t=*s.begin();
s.erase(s.begin());
if(!fro[t.p]){
if(a[t.p]>0){
ans-=t.av;
now--;
}
fro[nxt[t.p]]=0;
}else if(!nxt[t.p]){
if(a[t.p]>0){
ans-=t.av;
now--;
}
nxt[fro[t.p]]=0;
}else{
ans-=t.av;
ll x=fro[t.p],y=nxt[t.p];
fro[t.p]=fro[x];
nxt[t.p]=nxt[y];
nxt[fro[x]]=t.p;
fro[nxt[y]]=t.p;
//cout<<x<<"!"<<y<<endl;
t.av=abs(a[x]+a[y])-t.av;
if(a[t.p]>0){
a[t.p]=-t.av;
}else{
a[t.p]=t.av;
}
now--;
s.insert(t);
s.erase(s.find(gift(abs(a[x]),x)));
s.erase(s.find(gift(abs(a[y]),y)));
}
}
printf("%lld\n",ans);
return 0;
}
/*
20 4
5 -1 3 6 -4 -9 -5 2 1 -5 -3 3 -5 96 -6 -15 -1 2 -2 2
*/