[kuangbin带你飞]专题十六 KMP & 扩展KMP & Manacher J (kmp扩展)

来源:互联网 发布:解压缩工具 for mac 编辑:程序博客网 时间:2024/05/16 12:57

Link:https://vjudge.net/contest/70325#problem/J

题意:Write a program that, when given strings s1 and s2, finds the longest prefix of s1 that is a suffix of s2.(求s1的最长前缀 同时是s2的后缀.)

思路:求s2的每个后缀与s1的公共前缀,kmp扩展.

#include <cstdio>#include <cstring>#include <algorithm>using namespace std;int const maxn=50000+5;char str[maxn];char mode[maxn];int nextt[maxn],extend[maxn];void getNext(char mode[],int nextt[],int modeLen){int i,a,p;a=p=0,nextt[0]=modeLen;for(i=1;i<modeLen;i++){if(i>=p || i+nextt[i-a]>=p){if(i>=p)p=i;while(p<modeLen && mode[p]==mode[p-i]) ++p;nextt[i]=p-i;a=i;}else nextt[i]=nextt[i-a];}}void getExtend(char str[],int strLen,int extend[],char mode[],int modeLen){getNext(mode,nextt,modeLen);int a=0,p=0,sum=0;for(int i=0;i<strLen;i++){if(i>=p || i+nextt[i-a]>=p){if(i>=p) p=i;while(p<strLen && p-i<modeLen && str[p]==mode[p-i])p++;extend[i]=p-i,a=i;}else extend[i]=nextt[i-a];}}int main(){while(scanf("%s",mode)!=EOF){scanf("%s",str);int strLen=strlen(str);int modeLen=strlen(mode);getExtend(str,strLen,extend,mode,modeLen);bool bo=false;for(int i=0;i<strLen;i++){//printf("%d ",extend[i]);if(strLen-i == extend[i]){printf("%s",str+i);printf(" %d\n",extend[i]);bo=true;break;}}if(bo==false)printf("0\n");}return 0;}


阅读全文
0 0