优化:
(1)如果以i开头的长度为l的序列没有匹配序列,那么比l更长的序列一定不会有解,可以直接跳过。
1 (1)纯模拟-一次过
2 #include<iostream>
3 using namespace std;
4 int n;
5 int s[5001];
6 int main()
7 {
8 freopen("theme.in","r",stdin);
9 freopen("theme.out","w",stdout);
10 int i,j;
11 scanf("%d",&n);
12 for (i=0;i<n;++i)
13 scanf("%d",&s[i]);
14 int Max=1;
15 for(int i=0;i+2*Max-1<n;++i)
16 {
17 for(int j=i+Max-1;j+Max-1<n;++j)
18 {
19 int k=1;
20 while(1)
21 {
22 if(i+Max>=j)break;
23 if(s[i+k]-s[j+k]==s[i]-s[j])
24 {
25 k++;
26 if(k>Max)Max=k;
27 }
28 else break;
29 }
30 }
31 }
32 if(Max>=5)printf("%d\n",Max);
33 else printf("0\n");
34 return 0;
35 }
1 (2)动态规划
2 //空间不够
3 #include<iostream>
4 using namespace std;
5 int n;
6 char s[5001];
7 char dp[5001][5001];
8 int main()
9 {
10 freopen("theme.in","r",stdin);
11 freopen("theme.out","w",stdout);
12 int i,j;
13 scanf("%d",&n);
14 for (i=0;i<n;++i)
15 scanf("%d",&s[i]);
16 for(i=0;i<n;++i)
17 for(j=0;j<n;++j)
18 dp[i][j]=1;
19 int Max=1;
20 for(i=n-2;i>=0;--i)
21 for(j=n-2;j>=0;--j)
22 {
23 if(i==j)continue;
24 if(i+dp[i+1][j+1]>=j)continue;
25 if(s[j+1]-s[j]==s[i+1]-s[i])
26 dp[i][j]=dp[i+1][j+1]+1;
27 if(dp[i][j]>Max)Max=dp[i][j];
28 }
29 if(Max>=5)printf("%d\n",Max);
30 else printf("0\n");
31 return 0;
32 }