题目地址:点击打开链接http://poj.org/problem?id=1961
百万级字符串..无从下手,T到死
从网上查到要用KMP。。我之前也是看过的,欺负我读书少么,KMP与这个题有神马联系。
题目分析:该题用到了next数组,next数组代表的是"前缀"和"后缀"的最长的共有元素的长度(必然小于本身长度),为何用到它可能有些难以理解,慢慢来~
从结果逆推,若一个字符串(len=N)由某个子串(len=x)重复K次得到,则它的next数组值必然为(k-1)*x,这样就得到了K = N / (N - next[N]);
事实上,如果某一个字符串(len=N)的next数组值为x,并且有N整除(N-x),令L=N-x,由前缀后缀的对应关系,即可递推得:
S[(K-1)L+1...KL] = ... = S[2L+1...3L] = S[L+1...2L] = S[1...L]
#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;
char a[1000005];
int next[1000005];//从0开始
void makeNext(const char P[],int next[])
{
int q,k;
int m = strlen(P);
next[0] = 0;
for (q = 1,k = 0; q < m; ++q)
{
while(k > 0 && P[q] != P[k])
k = next[k-1];
if (P[q] == P[k])
{
k++;
}
next[q] = k;
}
}
int kmp(const char T[],const char P[],int next[])
{
int n,m;
int i,q;
n = strlen(T);
m = strlen(P);
makeNext(P,next);
for (i = 0,q = 0; i < n; ++i)
{
while(q > 0 && P[q] != T[i])
q = next[q-1];
if (P[q] == T[i])
{
q++;
}
if (q == m)
{
printf("Pattern occurs with shift:%d\n",(i-m+1));
}
}
}
int main()
{
int n;
for(int ii=1;;ii++)
{
cin>>n;
if(n==0)
{
break;
}
else{
cin>>a;
cout<<"Test case #"<<ii<<endl;
makeNext(a,next);
for(int i=2;i<=n;i++)
{
if(i%(i-next[i-1])==0&&i/(i-next[i-1])>1)
{
cout<<i<<" "<<i/(i-next[i-1])<<endl;
}
}
cout<<endl;
}
}
return 0;
}
P.S. KMP是直接找的板,next数组是从0开始定义的。
参考: http://www.cppblog.com/menjitianya/archive/2014/06/20/207354.html
http://www.cnblogs.com/c-cloud/p/3224788.html