题目:
-
5 2 3 2 3 2
样例输出 -
2
描述
You are given a sequence of integers, A = a1, a2, ... an. A consecutive subsequence of A (say ai, ai+1 ... aj) is called a "repeated sequence" if it appears more than once in A (there exists some positive k that ai+k = ai, ai+k+1 = ai+1, ... aj+k = aj) and its appearances are not intersected (i + k > j).
Can you find the longest repeated sequence in A?
输入
Line 1: n (1 <= n <= 300), the length of A.
Line 2: the sequence, a1 a2 ... an (0
<= ai <= 100).
输出
The length of the longest repeated sequence.
将运算中的局部结果保存在一个二维数组mark[][]中,mark[i][j]表示与子序列ai, ai+1 ... aj重复的下个子序列中首个数字的索引,
mark[i][j+1]由mark[i][j]很容易得到。
int LongestRepeatedSequence(vector arr, int n)
{
static int mark[300][300];
int maxNum = 0;
for (int i = 0; i < n; i++)
{
for (int j = i+1; j < n; j++)
{
if (arr[j] == arr[i])
{
mark[i][i] = j;
maxNum = 1;
break;
}
}
}
for (int i = 1; i < n; i++)
{
for (int j = 0; j < n-i; j++)
{
int k = mark[j][j+i-1];
while (k != 0)
{
if (k+i < n && arr[j+i] == arr[k+i])
{
mark[j][j+i] = k;
break;
}
else if (k+i == n)
break;
else
k = mark[k][k+i-1];
}
}
for (int j = 0; j < n-i; j++)
{
int k = mark[j][j+i];
while (k != 0)
{
if (j+i < k)
{
maxNum = i+1;
break;
}
else
k = mark[k][k+i];
}
}
}
return maxNum;
}
本文介绍了一种寻找给定整数序列中最长重复子序列的有效算法。通过使用二维数组记录局部结果,该算法能在多项式时间内解决问题。文章还提供了一个具体的实现示例,并通过样例输入输出展示了算法的应用。
4341

被折叠的 条评论
为什么被折叠?



