【学姐的胡策】训练8.18(KMP+dp)

来源:互联网 发布:叙利亚2017 知乎 编辑:程序博客网 时间:2024/04/28 17:17

题目:学姐的原题

题意:给定字符串s,输出前缀后缀相等的长度 并 找到他们在字符串中出现的次数

题解:

第一问是KMP原题,第二问是一个巧妙的dp,值得思考

代码:

#include <cstdio>#include <cstring>#include <iostream>#define N 100005using 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]]);}



原创粉丝点击