HDU2594 Simpsons ' Hidden talents "KMP"

Source: Internet
Author: User

Topic Links:

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


Main topic:

Give you two strings of S1 and S2, which is the longest string and length of both the S1 prefix and the S2 suffix.


Ideas:

KMP algorithm next[j] = = k is the essence of the current letter mismatch, the pattern string of the first K (s0~sk-1) and position J before

K-item (SJ-1-K~SJ-1) is equal, this K-value is all that satisfies the above situation maximum. So the meaning of Next[len]

is the longest prefix of the pattern string and the length of the string equal to the suffix.

Using the nature of next[], the string S2 is connected to the S1 behind. Next[] Array for S1. Well, now the Next[len]

is the longest length of the S1 prefix and S2 suffix, which is only full when the length of the <= string S1 and the length of the S2

of the foot. If the above conditions are not met, the found string is not a substring of S1 or S2. Let Len = Next[len] continue to check

Find the longest length that satisfies the condition. Find the string that satisfies the maximum length of the request, output S0~s (len-1).


AC Code:

#include <iostream> #include <algorithm> #include <cstdio> #include <cstring>using namespace Std;char s1[100010],s2[50010];int next[100010],len,len1,len2;void GetNext (char *s) {    int i = 0,j =-1;    Next[0] =-1;    while (i <= len)    {        if (j = =-1 | | s[i] = = S[j])        {            i++,j++;            Next[i] = j;        }        else            j = next[j];    }} int main () {    while (cin >> s1 >> S2)    {        len1 = strlen (S1);        Len2 = strlen (s2);        strcat (S1,S2);        Len = len1 + len2;        GetNext (S1);        while (Next[len] > Len1 | | Next[len] > Len2)            len = Next[len];        len = Next[len];        for (int i = 0; i < len; ++i)            cout << s1[i];        if (len)            cout << ';        cout << len << endl;    }    return 0;}


HDU2594 Simpsons ' Hidden talents "KMP"

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.