51nod 1053 最大M子段和 V2[贪心][链表][堆]

思路

#include<cstdio>
#include<queue>
#include<algorithm>
#define ABS(x) (x>0?x:-x)
#define N 50000
#define LL long long
using namespace std;

int n,m,l[N+5],r[N+5];
LL v[N+5];
struct node
{
    int p;
    bool operator < (const node &x) const
    {
        return ABS(v[p])>ABS(v[x.p]);
    }
};

priority_queue<node>heap;

int main()
{
    scanf("%d %d",&n,&m);
    int cnt=0,now=0;
    LL ans=0,x,V=0;
    for(int i=1;i<=n;++i)
    {
        scanf("%lld",&x);
        if(x==0) continue;
        if(V==0) {V=x;continue;}
        if(x>0)
            {if(V>0) V+=x;else v[++cnt]=V,V=x;}
        if(x<0)
            {if(V<0) V+=x;else v[++cnt]=V,V=x;}
    }
    v[++cnt]=V;
    for(int i=1;i<=cnt;++i)
    {
        if(v[i]>0) ++now,ans+=v[i];
        l[i]=i-1,r[i]=i+1;heap.push((node){i});
    }
    l[0]=0,r[0]=1,l[cnt+1]=cnt,r[cnt+1]=cnt+1;
    int tmp,L,R;
    while(now>m)
    {
        tmp=heap.top().p;heap.pop();
        if(l[r[tmp]]!=tmp||r[l[tmp]]!=tmp) continue;
        if(!v[tmp]||(v[tmp]<0&&(l[tmp]<1||r[tmp]>cnt))) continue;
        ans-=ABS(v[tmp]),--now;
        v[tmp]=v[tmp]+v[l[tmp]]+v[r[tmp]];
        L=l[l[tmp]],R=r[r[tmp]];
        l[tmp]=L,r[tmp]=R,r[L]=tmp,l[R]=tmp;
        heap.push((node){tmp});
    }
    printf("%lld",ans);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值