Algorithm title: Hdu 2594 Simpsons ' Hidden talents (KMP)

Source: Internet
Author: User
Tags strlen

Link:

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

The main effect of the topic:

Give two strings S1 and S2, and find the longest string that is the prefix of the S1 and is the S2 suffix.

Analysis and Summary:

Really understand good KMP algorithm, this is the water problem.

First, the mismatch function of S1 is obtained, and then the s1 string is searched in S2.

In the search for strings, there is a state value of J, which represents the number of S1 characters that are currently matched in S2. So, after all matches, the last J value is the longest string that matches the end of the last character of S2 and the prefix of the S1. That's the answer you asked for.

There is another way:

There are a number of online S1 seems to be the combination of the S2 and S3, and then to S3 their own next, the principle is the same.

Code:

 #include <iostream> #include <cstdio> #include <cstring> using namespace std;  
const int MAXN = 50005;  
Char S1[MAXN];  
Char S2[MAXN];  
      
int F[MAXN];  
    void Getfail (char *p, int *f) {int n=strlen (p);  
    f[0]=f[1]=0;  
        for (int i=1; i<n; ++i) {int j=f[i];  
        while (J && P[i]!=p[j]) j=f[j];  
    F[I+1] = p[i]==p[j]?1+j:0;  
    an int find (char *t,char *p,int *f) {getfail (p,f);  
    int N=strlen (T);  
    int M=strlen (p);  
    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;  
} return J;  
        int main () {while (scanf ("%s%s", S1,S2)!=eof) {int x=find (S2,S1,F);  
        if (!x) puts ("0");  
            else{int Len=strlen (S2);  
        printf ("%s%d\n", s2+len-x,x);  
} return 0; }

See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/sjjg/

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.