687. Repeats

Problem code: REPEATS

A string s is called an (k,l)-repeat if s is obtained by concatenating k>=1 times some seed string t with length l>=1. For example, the string

s = abaabaabaaba

is a (4,3)-repeat with t = aba as its seed string. That is, the seed string t is 3 characters long, and the whole string s is obtained by repeating t 4 times.

Write a program for the following task: Your program is given a long string u consisting of characters ‘a’ and/or ‘b’ as input. Your program must find some (k,l)-repeat that occurs as substring within u with k as large as possible. For example, the input string

u = babbabaabaabaabab

contains the underlined (4,3)-repeat s starting at position 5. Since u contains no other contiguous substring with more than 4 repeats, your program must output the maximum k.

Input

In the first line of the input contains H- the number of test cases (H <= 20). H test cases follow. First line of each test cases is n - length of the input string (n <= 50000), The next n lines contain the input string, one character (either ‘a’ or ‘b’) per line, in order.

Output

For each test cases, you should write exactly one interger k in a line - the repeat count that is maximized.

Example

Input:
1
17
b
a
b
b
a
b
a
a
b
a
a
b
a
a
b
a
b Output:
4
 #include <iostream>
#include <stdio.h>
#include <math.h>
#include <vector>
#include <string.h>
using namespace std;
#define N 50002
char a[N];
int c[N],d[N],e[N],sa[N],height[N],n,b[N],m,dp[N][];
int cmp(int *r,int a,int b,int l)
{
return r[a]==r[b]&&r[a+l]==r[b+l];
}
void da()
{
int i,j,p,*x=c,*y=d,*t;
memset(b,,sizeof(b));
for(i=; i<n; i++)b[x[i]=a[i]]++;
for(i=; i<m; i++)b[i]+=b[i-];
for(i=n-; i>=; i--)sa[--b[x[i]]]=i;
for(j=,p=; p<n; j*=,m=p)
{
for(p=,i=n-j; i<n; i++)y[p++]=i;
for(i=; i<n; i++)if(sa[i]>=j)y[p++]=sa[i]-j;
for(i=; i<n; i++)e[i]=x[y[i]];
for(i=; i<m; i++)b[i]=;
for(i=; i<n; i++)b[e[i]]++;
for(i=; i<m; i++)b[i]+=b[i-];
for(i=n-; i>=; i--)sa[--b[e[i]]]=y[i];
for(t=x,x=y,y=t,p=,x[sa[]]=,i=; i<n; i++)
x[sa[i]]=cmp(y,sa[i-],sa[i],j)?p-:p++;
}
}
void callheight()
{
int i,j,k=;
b[]=;
for(i=; i<n; i++)b[sa[i]]=i;
for(i=; i<n-; height[b[i++]]=k)
for(k?k--:,j=sa[b[i]-]; a[i+k]==a[j+k]; k++);
}
int fun(int i,int j)
{
i=b[i];
j=b[j];
if(i>j)swap(i,j);
i++;
int k=(int)(log(j-i+1.0)/log (2.0));
return min(dp[i][k],dp[j-(<<k)+][k]);
}
void initrmq()
{
int i,j;
memset(dp,,sizeof(dp));
for(i=; i<=n; i++)
dp[i][]=height[i];
for(j=; (<<j)<=n; j++)
for(i=; i+(<<j)<=n; i++)
dp[i][j]=min(dp[i][j-],dp[i+(<<(j-))][j-]);
}
int main()
{
int t,i,j,r;
scanf("%d",&t);
for(r=; r<t; r++)
{
scanf("%d",&n);
for(i=; i<n; i++)a[i]=getchar(),a[i]=getchar();
a[n++]='\0';
m=;
da();
callheight();
initrmq();
int max=;
for(i=; i<n/; i++)
{
for(j=; j+i<n; j+=i)
{
int k=fun(j,j+i);
int kk=k/i+;
int tt=i-k%i;
tt=j-tt;
if (tt>=&&k%i!=)
if(fun(tt,tt+i)>=k)
kk++;
if(max<kk)
{
max=kk;
}
}
}
printf("%d\n",max);
}
}
04-16 11:54
查看更多