题目:学姐的原题
题意:给定字符串s,输出前缀后缀相等的长度 并 找到他们在字符串中出现的次数
题解:
第一问是KMP原题,第二问是一个巧妙的dp,值得思考
代码:
#include <cstdio>
#include <cstring>
#include <iostream>
#define N 100005
using namespace std;
int len[N],t[N],l,dp[N];
char st[N];
void sp()
{
int i,j;
t[0]=-1;
for (i=0;i<l;i++)
{
j=t[i];
while (j!=-1 && st[i]!=st[j]) j=t[j];
t[i+1]=++j;
}
}
int main()
{
int i;
gets(st);
l=strlen(st);
sp();
int j=l,hh=0;
while (j)
{
len[++hh]=j;
j=t[j];
}
for (i=l;i;i--)
{
dp[i]++;
dp[t[i]] += dp[i];
}
printf("%d\n",hh);
for (i=hh;i>=1;i--)
printf("%d %d\n",len[i],dp[len[i]]);
}