zoukankan      html  css  js  c++  java
  • HDU 2594 Simpsons’ Hidden Talents(KMP)

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

    题意:
    给出两个字符串,求最长的子串使得该子串同时是第一个字符串的前缀和第二个字符串的后缀。

    思路:
    这道题本来就是KMP算法的一个应用吧。

    在用kmp进行匹配时,文本串的最后一串字符肯定和匹配串起始的一串字符是相等的。

     1 #include<iostream>
     2 #include<algorithm>
     3 #include<cstring>
     4 #include<cstdio>
     5 #include<vector>
     6 #include<stack>
     7 #include<queue>
     8 #include<cmath>
     9 #include<map>
    10 #include<set>
    11 using namespace std;
    12 typedef long long ll;
    13 typedef pair<int,int> pll;
    14 const int INF = 0x3f3f3f3f;
    15 const int maxn = 50000 + 5;
    16 
    17 int n,m;
    18 int ans;
    19 int f[maxn];
    20 char s1[maxn],s2[maxn];
    21 
    22 
    23 void kmp(char* T, char* P)
    24 {
    25     f[0]=0; f[1]=0;
    26     for(int i=1;i<m;i++)
    27     {
    28         int j=f[i];
    29         while(j && P[i]!=P[j])  j=f[j];
    30         f[i+1]= P[i]==P[j]?j+1:0;
    31     }
    32 
    33     int j=0;
    34     for(int i=0;i<n;i++)
    35     {
    36         while(j && P[j]!=T[i])  j=f[j];
    37         if(P[j]==T[i])  j++;
    38         if(i==n-1)  ans=j;
    39         if(j==m)  j=f[j];
    40     }
    41 }
    42 
    43 int main()
    44 {
    45     //freopen("in.txt","r",stdin);
    46     while(~scanf("%s%s",s2,s1))
    47     {
    48         n=strlen(s1);
    49         m=strlen(s2);
    50         ans=-1;
    51         kmp(s1,s2);
    52         if(!ans)  puts("0");
    53         else
    54         {
    55             for(int i=0;i<ans;i++)  printf("%c",s2[i]);
    56             printf("% d
    ",ans);
    57         }
    58     }
    59     return 0;
    60 }
  • 相关阅读:
    FileZilla
    dos2unix转换从win下vimruntime下的文件
    在 MFC SDI 程序中实现多语言程序界面
    AheadLib 2.2.150
    F982,F983班数理逻辑期末考试试题
    论文公式规范。
    Servlet/JSP配置详解
    COM沉思录(八)
    XML配置文件的读取处理
    天使和魔鬼(转载)
  • 原文地址:https://www.cnblogs.com/zyb993963526/p/7662896.html
Copyright © 2011-2022 走看看