USACO Section5.1 theme

Problem Summary

Given an array of N integers, find the maximal length of its “repeating” subsequence.

“A repeats B” means that subsequence A and B meet the following conditions:

  1. A and B are not overlapping
  2. A and B have the same length N, where N>=5
  3. There is a constant c, s.t. A[i]+c=B[i], 1<=i<=N

Solution

This is a pretty staight forward dynamic programming problem.

Let diff[i]=seq[i]-seq[i-1],2<i<=n. Then the problem is equivalent to finding the maximal length of repeating subsequence of diff.

Let f[i][j] be the maximal length of repeating subsequence ending at i and j in the sequence diff. Apparently, f[i][j] has the same value with f[j][i]. Then the answer to the original problem is max{f[i][j]}+1, 2<=i<n, i+1<j<=n

The dynamic programming equations are:

f[i][j]=f[i-1][j-1]+1, if diff[i]==diff[j] && f[i-1][j-1]<=j-i-2
f[i][j]=f[i-1][j-1], if diff[i]==diff[j] && f[i-1][j-1]==j-i-2
f[i][j]=0, if diff[i]!=diff[j]

Well, for any i, f[i][j] only depends on f[i-1][j], so we can rewrite the eqations:

f[j]=f[j-1]+1, if diff[i]==diff[j] && f[j-1]<=j-i-2
f[j]=f[j-1], if diff[i]==diff[j] && f[j-1]==j-i-2
f[j]=0, if diff[i]!=diff[j]

Using the new equations, we need to do the inner loop backwards. And we can save a lot of space.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <iostream>
#include <fstream>
using namespace std;
const int maxn = 5002;
int n,diff[maxn];
int f[maxn];
int main()
{
fstream fin("theme.in",ios::in);
fstream fout("theme.out",ios::out);
fin>>n;
int pre=0,cur=0;
for(int i=1;i<=n;i++)
{
fin>>cur;
diff[i]=cur-pre;
pre=cur;
}
int ans=0;
for(int j=3;j<=n;j++)
f[j]=(diff[j]==diff[2]);
for(int i=3;i<=n;i++)
{
for(int j=n;j>=i+2;j--)
{
if(diff[i]==diff[j])
{
if(f[j-1]<=j-i-2)
f[j]=f[j-1]+1;
else
f[j]=f[j-1];
}
else
f[j]=0;
ans=ans>f[j] ? ans:f[j];
}
}
ans++;
if(ans<5) ans=0;
fout<<ans<<endl;
fin.close();
fout.close();
return 0;
}