您的位置:首页 > 产品设计 > UI/UE

Longest Repeated Sequence

2014-04-06 11:20 351 查看
时间限制: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


未测试,要注意的是search参数为4个迭代器,而end迭代器要指向范围的下一个元素,故搜索范围为A.begin() + i, A.begin() + i + k+1。

循环条件为i+k<n,条件太弱。

当剩余搜索的序列长度小于要搜索的子序列长度则已不成立,即:

(i+k)-i<=n-(i+k+1)

i+2k+1<=n

#include <iostream>
#include <map>
#include <vector>
#include <string>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <cmath>
using namespace std;

int main()
{
int n;
cin >> n;
vector<int> A(n);
for (size_t i = 0; i != n; ++i)
cin >> A[i];
int len=0, k=0;
for (size_t i = 0; i != n; ++i)
{
//while (i + k < n)
while (i+2*k+1<=n)
{
// beg end beg end!! need + 1
if (search(A.begin() + i + k + 1, A.end(), A.begin() + i, A.begin() + i + k+1) != A.end())
{
len = max(k+1, len);
++k;
}
else
break;
}
k = 0;
}
cout << len << endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: