题解:P10977 Cut the Sequence
zhouruoheng · · 题解
Cut the Sequence
P10977 Cut the Sequence
前言
单调队列优化 dp 的好题,思维难度大细节多。因为觉得自己看不懂其他题解,在看完 y 总的讲解后豁然开朗,所以写这篇题解来巩固一下。包括完整的细节分析和思考过程,或许很多大佬都不需要 qwq。叠甲完毕,下面开始正文。
分析
先考虑无解的情况,将单个元素分成段,每段的和最小,如果还是大于
状态表示
题意和给出的信息都很简单,看
状态转移
考虑
优化
上面这个方程显然是
首先注意到
设最后一段的贡献为
- 若
a_i 加入最后一段, -
- 若
a_i 自己新开一段,有f_i=f_{i-1}+a_i 。
因为序列中的数大于等于
蓝书上的话:
DP 转移优化的指导思想就是及时排除不可能的决策,保持候选集合的高度有效性和秩序性。
所以不妨设
设最后一段的贡献为
- 当
k_0 \le j < k_1 时,a_{max}=a_{max_1} ,f_j 最小值肯定是在j=k_0 时,所以最优的j 为k_0 。 - 当
k_1 \le j < k_2 时,a_{max}=a_{max_2} ,最优的j 为k_1 。 - 当
k_2 \le j < k_3 时,a_{max}=a_{max_3} ,最优的j 为k_2 。
所以最优决策
所以
- 取
k_0 时,k_0 为满足\sum_{k=j+1}^{i} a_k \le m 的最小的j 。 - 取
k_1,k_2,k_3,\dots 时,满足a_j=\max_{k=j}^{i} a_k 。
情况
情况
有一个细节,只有当单调队列中的元素大于一时,才能出现第二种情况,思考一下就能理解。
时间复杂度瓶颈主要在于 multiset 的操作,时间复杂度为
代码还是很好写的。
code
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <vector>
#include <queue>
#include <map>
#include <set>
using namespace std;
typedef long long ll;
const int N=1e5+5;
int n;
ll m;
ll a[N],f[N];
int q[N];
multiset<ll> st;
void solve()
{
cin>>n>>m;
for(int i=1;i<=n;i++)
{
cin>>a[i];
if(a[i]>m) //无解的情况
{
cout<<"-1\n";
return ;
}
}
int l=1,r=0;
ll sum=0;
for(int i=1,j=1;i<=n;i++)
{
sum+=a[i];
while(sum>m)
{
sum-=a[j++];
while(l<=r&&q[l]<j)
{
if(l<r) st.erase(f[q[l]]+a[q[l+1]]);
l++;
}
}
while(l<=r&&a[q[r]]<=a[i])
{
if(l<r) st.erase(f[q[r-1]]+a[q[r]]);
r--;
}
q[++r]=i;
if(l<r) st.insert(f[q[r-1]]+a[q[r]]);
f[i]=f[j-1]+a[q[l]];//处理后j=k0+1
if(st.size()) f[i]=min(f[i],*st.begin());
}
cout<<f[n]<<'\n';
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("1.in","r",stdin);
freopen("1.out","w",stdout);
#endif
ios::sync_with_stdio(0);
cin.tie(0);cout.tie(0);
solve();
return 0;
}
后记
思维量大,但是代码简单。利用题目性质进行优化 dp。考虑最优决策满足的条件。双指针和单调队列维护。multiset 维护单调队列贡献。
求审核大大通过 qwq。