Divide the sequence (recursion)

Divide the sequence

Insert picture description here
Insert picture description here

Problem solving ideas

Setting fi f_ifiIndicates the minimum number of segments that can be divided from one to i,
then there is a transfer equation

f i = m i n ( f b i − 1 , f c i − 1 ) + 1 f_i=min(f_{b_i}−1,f_{c_i}−1)+1 fi=m i n ( fbi1,fci1)+1
b i b_i biRepresents the starting point of a monotonically increasing segment ending with i
ci c_iciIndicates the starting point of a monotonically decreasing paragraph ending with i

AC code

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int n,last,a,b[100005],c[100005],f[100005];
int main()
{
    
    
	scanf("%d%d",&n,&last);
	b[1]=c[1]=1;//初值
	for(int i=2;i<=n;i++)//预处理
	{
    
    
		scanf("%d",&a);
		if(a>=last)b[i]=b[i-1];
		else b[i]=i;
		if(a<=last)c[i]=c[i-1];
		else c[i]=i;
		last=a;
	}
	memset(f,0x7fff,sizeof(f));//初值
	f[0]=f[1]=0;
	for(int i=1;i<=n;i++)//递推
	 f[i]=min(f[b[i]-1]+1,f[c[i]-1]+1);
	printf("%d",f[n]);
	return 0;
}

Thank you

Guess you like

Origin blog.csdn.net/weixin_45524309/article/details/111594387