bzoj5424(DP)

题目链接

https://www.lydsy.com/JudgeOnline/problem.php?id=5424

题解

这个首先考虑最暴力的做法,设 $d[i][j]$ 为到 $i$ 选了$j$ 个数的最小代价,那么

其中 $cost$ 需要分两种情况考虑。。一种是 $cost=0$ ,那么

这个就是求区间最值,直接单调队列

另一种是前缀最值

这个求前缀和即可。。




代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/**
*         ┏┓    ┏┓
*         ┏┛┗━━━━━━━┛┗━━━┓
*         ┃       ┃  
*         ┃   ━    ┃
*         ┃ >   < ┃
*         ┃       ┃
*         ┃... ⌒ ...  ┃
*         ┃ ┃
*         ┗━┓ ┏━┛
*          ┃ ┃ Code is far away from bug with the animal protecting          
*          ┃ ┃ 神兽保佑,代码无bug
*          ┃ ┃           
*          ┃ ┃       
*          ┃ ┃
*          ┃ ┃           
*          ┃ ┗━━━┓
*          ┃ ┣┓
*          ┃ ┏┛
*          ┗┓┓┏━━━━━━━━┳┓┏┛
*           ┃┫┫ ┃┫┫
*           ┗┻┛ ┗┻┛
*/

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<queue>
#include<map>
#include<stack>
#include<set>
#include<bitset>
#include<cmath>
#include<assert.h>
#define inc(i,l,r) for(int i=l;i<=r;i++)
#define dec(i,l,r) for(int i=l;i>=r;i--)
#define link(x) for(edge *j=h[x];j;j=j->next)
#define mem(a) memset(a,0,sizeof(a))
#define ll unsigned long long
#define succ(x) (1ll<<x)
#define lowbit(x) (x&(-x))
#define sqr(x) ((x)*(x))
#define mid (x+y>>1)
#define NM 100005
#define nm 400005
using namespace std;
const double pi=acos(-1);
const int inf=1e9+9;
const double eps=1e-8;
ll read(){
ll x=0,f=1;char ch=getchar();
while(!isdigit(ch)){if(ch=='-')f=-1;ch=getchar();}
while(isdigit(ch))x=x*10+ch-'0',ch=getchar();
return f*x;
}




int n,m,ans;
int q[NM],qh,qt,d[2][NM],_t;
int a[NM],cnt;


int main(){
n=read();m=read();
inc(i,1,n)a[i]=read()+a[i-1];
if(a[n]>m)ans=a[n];else ans=0;
inc(i,1,n)d[_t][i]=inf;
for(int j=1;j*(j+1)<n*4;j++){
_t^=1;mem(d[_t]);cnt=0;
int t=d[_t^1][0];
d[_t][0]=inf;
q[qh=qt=1]=0;
inc(i,1,n){
while(a[i-1]-a[cnt]>m)t=min(t,d[_t^1][cnt]-a[cnt]),cnt++;
while(qh<=qt&&q[qh]<cnt)qh++;
d[_t][i]=min(t+a[i-1],d[_t^1][q[qh]])+j*(a[i]-a[i-1]);
if(a[n]-a[i]>m)ans=min(ans,d[_t][i]+a[n]-a[i]);
else ans=min(ans,d[_t][i]);
while(qh<=qt&&d[_t^1][i]<=d[_t^1][q[qt]])qt--;
q[++qt]=i;
}
//inc(i,1,n)printf("%d ",d[_t][i]);putchar('\n');
}
printf("%d\n",ans);
return 0;
}