原题如下:
题目2 : Longest Repeated Sequence
时间限制:
10000ms
单点时限:
1000ms
内存限制:
256MB
-
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.
#define _CRT_SECURE_NO_DEPRECATE
#include"stdafx.h"
#include <stdio.h>
int main(){
int len,maxLen = 0,curLen,step;
int value[300];
scanf("%d",&len);
for(int i = 0; i < len;i++)
scanf("%d",&value[i]);
for(int i = 0 ; i < len; i++){
for(int j = i + 1; j < len; j++){
if(value[i] == value[j] && (j - i) > maxLen ){
curLen = j - i;
step = 0;//记录向前走的步长,用于返回
for(int k = 0; k < curLen; k++){
if(value[i] != value[j]){
break;//当前curlen的重复子串不存在
}
i++;
j++;
step++;
}
if(step == curLen){//当前curLen的重复子串存在
maxLen = curLen;
}
i = i - step;
j = j - step;
}
}
}
printf("%d\n",maxLen);
}
同样,上述代码也没有经过在线测试,有错误还望指正。另外,此题应该有更加高效的算法,还望大牛们不吝赐教!