微软编程一小时 题目2: Longest Repeated Sequence
2024-08-28 22:32:20
题目2 : Longest Repeated Sequence
时间限制:10000ms
单点时限:1000ms
内存限制:256MB
描述
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.
- 样例输入
-
5
2 3 2 3 2 - 样例输出
2 看到这个题,首先能够想到的思路有很多,KMP,后缀数组等等,然而限于时间限制,我暂时能够想到的方法就是暴搜了(-.-!请见谅): 首先有个关键问题需要注意一下, 本题是不可重叠最长子串的问题,不能直接套用后缀数组(参看《编程珠玑》p156),也不能直接套用kmp. (在后续博文中,我再给出其他的解法)。
由于是不可重叠最长子串的问题,如果原串的长度为L,那么子串长度Ls理论上能够达到的最大值为 floor(L/2). 本人思路如下:(如有问题,请各位指出,交流交流经验吧) 寻找数组中能够出现的首个最大长度重复子串的过程: Input L: 数组的长度
Input A: 待查找数组
Output maxlen: 最长重复子串的长度 for k <- L/2 to 2
for i <- 0 to L - k
for j <- i+ k to L
if comlen(A, i,j,L,k) // 判断长度为k的重复子串是否存在
maxLen <- k
return maxLen
return maxLen 源码如下:
/**********************************************
@author: lsc
@time: 2014-04-05
***********************************************/
#include <iostream>
using namespace std; /***********************************************
* comlen:
* i: 查找串T的起始位置
* j: 模式串P的起始位置
* size: 数组边界
* k: 子串长度
* 返回值:
* true: 存在长度为k的重复子串
* false: 不存在长度为k的重复子串
************************************************/
bool comlen(int a[], int i, int j,int size,int k)
{
int len = ;
while(i<size && j<size && a[i++] == a[j++])
{
++len;
if(len==k)
return true;
}
return false;
} /***********************************************
* LRS_base: 查找主逻辑
* maxlen: 记录最长重复子串长度
* arr: 带查找串
***********************************************/
int LRS_base(int arr[], int size)
{
int k,maxlen,i,j;
maxlen=; for(k=size/;k>=;k--)
{
for(i = ; i < size-k; ++i)
{
for( j = i+ k; j < size; ++j)
{
if(comlen(arr,i,j,size,k)==true)
{
maxlen = k;
return maxlen;
}
}
}
}
return maxlen;
} int main()
{
int a[]={},n;
cin>>n;
if(n<=||n>)
exit();
for(int i=;i<n;i++) cin>>a[i];
cout<<LRS_base(a,n)<<endl; return ;
}
最新文章
- 11.11光棍节工作心得——github/MVP
- ASP.NET中的XML和JSON
- 讲解版的导航高亮(新手福利)原生JS
- 【avalon】offsetParent
- Servlet和JAVA BEAN 分析探讨
- Ehcache(2.9.x) - API Developer Guide, Cache Extensions
- usb device selection
- java编译环境
- MySQL 5.6 解决InnoDB: Error: Table ";mysql";.";innodb_table_stats"; not found.问题
- 获取scrollTop兼容各浏览器的方法,以及body和documentElement
- VB 字符串函数总结
- 重置CentOS 7的Root密码
- Linux 6.4 设置yum 为centOS源
- java 打印近似圆
- sublime的插件
- 机器学习入门之python实现图片简单分类
- gnutls-3.5.18 static building for windows
- JS设计模式(10)职责链模式(重要)
- 项目无法运行iPhone5模拟器
- 做一个WINDOWS下破解WIFI。不须要Linux抓包!