【KMP】 HDU 2594 Simpsons’ Hidden Talents

来源:互联网 发布:c语言编写的聊天程序 编辑:程序博客网 时间:2024/06/05 17:54

点击打开链接

KMP中最后 j 的位置是S串的前缀位置

#include <cstdio>#include <cstring>#include <cstdlib>#include <string>#include <iostream>#include <algorithm>#include <sstream>#include <cmath>using namespace std;#include <queue>#include <stack>#include <vector>#include <deque>#define cler(arr, val)    memset(arr, val, sizeof(arr))#define FOR(i,a,b)  for(int i=a;i<=b;i++)#define IN   freopen ("in.txt" , "r" , stdin);#define OUT  freopen ("out.txt" , "w" , stdout);typedef long long  LL;const int MAXN = 60000;const int MAXM = 6000010;const int INF = 0x3f3f3f3f;const LL mod = 10e9+7;const double eps= 1e-8;#define lson l,m, rt<<1#define rson m+1,r,rt<<1|1int next[MAXN];char s[MAXN],c[MAXN];void getnext(int len){    int i=0,j=-1;    next[0]=j;    while(i<len)    {        if(j==-1||s[i]==s[j])            i++,j++,next[i]=j;        else j=next[j];    }}int KMP(int len,int len2){    int i=0,j=0;    if(len<len2) i=len2-len;    while(j<len&&i<len2)    {        if(j==-1||c[i]==s[j])        {            i++;            j++;        }        else            j=next[j];    }    return j;}int input(){    if(cin>>s>>c) return 1;    return 0;}int solve(){    int len=strlen(s);    int len2=strlen(c);    getnext(len);    int ans=KMP(len,len2);    if(ans==0)        cout<<0<<endl;    else cout<<c+len2-ans<<" "<<ans<<endl;}int main(){    while(input())        solve();    return 0;}


0 0