codeforces 255C Almost Arithmetical Progression

传送门
在这里插入图片描述
题意:求长度最长的锯齿形子序列。(非连续)
锯齿形:ab型 12121
解析:dp
dp[ i ][ j ] :表示 以a[i],a[j] 结尾的 符合条件的 子序列长度
dp[ i ][ j ] = dp[last][ i ]+1;
其中 a[last]==a[j] (头尾相同), last—i-----j
例子:12133212 j=8 i 从头推过来 推一遍就明白

#include<cstdio>
#include<cstring>
#include<string>
#include<string>
#include<cmath>
#include<iostream>
using namespace std;
int dp[5000][5000];
int b[5000];
int main()
{
	int n;
	scanf("%d",&n);
	for(int i=1;i<=n;i++)
		scanf("%d",&b[i]);
	memset(dp,0,sizeof(dp));
	int ans=-1;
	
	for(int j=1;j<=n;j++)				//两个数中的后一个数
		for(int i=0,last=0;i<j;i++)			//两个数中的前一个数
		{
			dp[i][j]=dp[last][i]+1;			//last 就是下面的头
			if(b[i]==b[j])					//头尾相同,可形成锯齿序列,时刻更新这个头
				last=i;
			ans=max(ans,dp[i][j]);
		}
		cout<<ans<<endl;
	return 0;
}
posted @ 2020-07-13 18:47  DuJunlong  阅读(8)  评论(0)    收藏  举报  来源