HDU 2594 — Simpsons’ Hidden Talents

来源:互联网 发布:淘宝售后客服工作规范 编辑:程序博客网 时间:2024/06/06 17:41

原题:http://acm.hdu.edu.cn/showproblem.php?pid=2594

题意:

给出两个字符串S1, S2,找出S1中最长的可以和S2的后缀匹配的前缀;


思路:

将S1作为模式串,S2作为目标串,用KMP就好,看到S2的最后一个字符时能匹配S1中的第几个字符;



#include<stdio.h>  #include<string.h>    const int maxn = 50005;  char T[maxn], P[maxn];  int f[maxn], n, m;    int find()  {      int j = 0;      for(int i = 0;i<n;i++)      {          while(j && T[i]!=P[j]) j = f[j];          if(T[i] == P[j]) j++;          if(i == n-1)           return j;      }   }    void getFail()  {      f[0] = f[1] = 0;      for(int i = 1;i<m;i++)      {          int j = f[i];          while(j && P[i]!=P[j]) j=f[j];          if(P[i] == P[j])          f[i+1] = j+1;          else          f[i+1] = 0;      }  }  int main(){while(scanf("%s%s", P, T)!=EOF){n = strlen(T);m = strlen(P);getFail();int ans = find();if(ans == 0)printf("0\n");elseprintf("%s %d\n", T+(n-ans), ans);}return 0;}



0 0