bzoj 2288 【POJ Challenge】生日礼物 双向链表+堆优化

2288: 【POJ Challenge】生日礼物

Time Limit: 10 Sec  Memory Limit: 128 MB
Submit: 1003  Solved: 317
[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

 

是贪心的做法

首先将符号相同的一段合并成一个值,为了处理方便一开始可以将序列中的0全部去掉

如 1 3 -1 -2 4 -1 变成 4 -3 4 -1

容易证明最后结果一定是取完整的一段

如果>0的段小于m那么就解决了

如果大于m

将这些段放入堆中按绝对值进行排序

获取堆中最小值将它和周围两段合并,这里要用到双向链表

因为如果这个值是正数,那么相当于不选它了

是负数的话相当于将它左右两段合并,这样都使得选取的段数-1

但是要考虑一个边界的问题

边上的负数不能取,因为就算取了它也不存在左右两段合并

而正数可以取,相当于不选它了

 

 1 #pragma GCC optimize(2)
 2 #pragma G++ optimize(2)
 3 #include<iostream>
 4 #include<algorithm>
 5 #include<cmath>
 6 #include<cstdio>
 7 #include<cstring>
 8 #include<queue>
 9 
10 #define pa pair<int,int>
11 #define ll long long
12 #define inf 10000007
13 #define N 100007
14 using namespace std;
15 inline int read()
16 {
17     int x=0,f=1;char ch=getchar();
18     while (ch<'0'||ch>'9'){if (ch=='-') f=-1;ch=getchar();}
19     while (ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
20     return x*f;
21 }
22 
23 struct cmp
24 {
25     bool operator()(pa a,pa b)
26     {
27         return abs(a.first)>abs(b.first);
28     }
29 };
30 priority_queue<pa,vector<pa>,cmp>q;
31 
32 int n,m,tot,ans,sum;
33 int a[N],nxt[N],pre[N];
34 bool mark[N];
35 
36 void del(int x)
37 {
38     mark[x]=1;
39     pre[nxt[x]]=pre[x];
40     nxt[pre[x]]=nxt[x];
41 }
42 int main()
43 {
44     n=read(),m=read(),tot=1;
45     for (int i=1;i<=n;i++)
46     {
47         int x=read();
48         if ((ll)a[tot]*x>=0)a[tot]+=x;
49         else a[++tot]=x;
50     }//这里相乘比较巧妙。
51     n=tot;
52     for (int i=1;i<=n;i++) 
53         if (a[i]>0) sum++,ans+=a[i];
54     for (int i=1;i<=n;i++)
55     {
56         nxt[i]=i+1;
57         pre[i]=i-1;
58         q.push(make_pair(a[i],i));
59     }
60     while (sum>m)
61     {
62         sum--;
63         while (mark[q.top().second]) q.pop();
64         int x=q.top().second;q.pop();
65         if (pre[x]!=0&&nxt[x]!=n+1) ans-=abs(a[x]);
66         else if (a[x]>0) ans-=a[x];else{sum++;continue;}
67         a[x]=a[pre[x]]+a[nxt[x]]+a[x];
68         del(pre[x]);del(nxt[x]);
69         q.push(make_pair(a[x],x));
70     }
71     printf("%d",ans);
72 }

 

转载于:https://www.cnblogs.com/fengzhiyuan/p/8486716.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值