POJ3017【Cut the Sequence】

Cut the Sequence

topic

Cut the Sequence


Parsing

Monotonic queue optimization DP is a good question
. First of all, we will take part of the points. Let us consider the naked DP first, and get the dynamic transfer equation:
dp[i]=min(dp[j]+max(a[k])(j<k<=i ))(1<=j<=i)
Obviously this O(N 2 ) DP must
consider the maximum value of monotonic queue optimization, AC
1, prefix sum optimization, O(1) interval sum
2, open longlong
3, there is When the value> m, output -1.
In fact, I heard that monotonic queue optimization can be stuck to O(n 2 ), but A is fine.

code:

#include<cstdio>
#include<deque>
#define ll long long
using namespace std;
ll min(ll x,ll y){
    
    return (x<y)?x:y;}
bool idigit(char x){
    
    return (x<'0'|x>'9')?0:1;}
inline ll read()
{
    
    
	ll num=0,f=1;
	char c=0;
	while(!idigit(c=getchar())){
    
    if(c=='-')f=-1;}
	while(idigit(c))num=(num<<1)+(num<<3)+(c&15),c=getchar();
	return num*f;
}
inline void write(ll x)
{
    
    
	ll F[20];
	ll tmp=x>0?x:-x;
	if(x<0)putchar('-');
	ll cnt=0;
	while(tmp>0){
    
    F[cnt++]=tmp%10+'0';tmp/=10;}
	while(cnt>0)putchar(F[--cnt]);
	if(x==0)putchar('0');
}//快读快输日常
ll n,m,a[100010],s[100010],dp[100010],k,l;
deque <ll> b;
int main()
{
    
    
	n=read(),m=read();
	for(ll i=1;i<=n;i++)
	{
    
    
		a[i]=read(),s[i]=s[i-1]+a[i];//s
		if(a[i]>m)
		{
    
    
			printf("-1");
			return 0;
		}//特判
	}
	dp[1]=a[1];
	k=1;
	for(ll i=1;i<=n;i++)
	{
    
    
		while(!b.empty()&&a[i]>=a[b.back()])b.pop_back();
		while(s[i]-s[k-1]>m&&k<i)++k;
		b.push_back(i);
		while(!b.empty()&&b.front()<k)b.pop_front();
		dp[i]=dp[k-1]+a[b.front()];
		for(int j=1;j<=b.size();j++)
		{
    
    
			l=b.front();
			b.pop_front();
			if(!b.empty())dp[i]=min(dp[i],dp[l]+a[b.front()]);
			b.push_back(l);
		}//单调队列优化
	}
	write(dp[n]);
	return 0;
}

Guess you like

Origin blog.csdn.net/zhanglili1597895/article/details/113105689