HDU

来源:互联网 发布:超越无限 知乎 编辑:程序博客网 时间:2024/06/03 18:47

Find the Shortest Common Superstring

Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 65535/65535 K (Java/Others)
Total Submission(s): 2126    Accepted Submission(s): 585


Problem Description
The shortest common superstring of 2 strings S1 and S2 is a string S with the minimum number of characters which contains both S1 and S2 as a sequence of consecutive characters. For instance, the shortest common superstring of “alba” and “bacau” is “albacau”.
Given two strings composed of lowercase English characters, find the length of their shortest common superstring. 
 

Input
The first line of input contains an integer number T, representing the number of test cases to follow. Each test case consists of 2 lines. The first of these lines contains the string S1 and the second line contains the string S2. Both of these strings contain at least 1 and at most 1.000.000 characters.
 

Output
For each of the T test cases, in the order given in the input, print one line containing the length of the shortest common superstring.
 

Sample Input
2albabacauresitamures
 

Sample Output
78
KMP模板题

#include<stdio.h>#include<string.h>#define maxn 1000010char s1[maxn],s2[maxn];int next[maxn];void get_next(char s[]){    int j=0,k=-1;    next[0]=-1;    int len=strlen(s);    while(j<=len)    {        if(s[j]==s[k]||k==-1)        {            ++j;            ++k;            if(s[j]!=s[k])                next[j]=k;            else                next[j]=next[k];        }        else            k=next[k];    }}int kmp(char a[],char b[],int len1,int len2){    get_next(b);    int i,j;    i=j=0;    while(i<len1)    {        if(j==-1||a[i]==b[j])        {            i++;            j++;        }        else            j=next[j];        if(j==len2)            return len2;    }    if(i==len1)        return j;    return 0;}int main(){    int n;    while(scanf("%d",&n)!=EOF)    {        while(n--)        {            memset(s1,'\0',sizeof(s1));            memset(s2,'\0',sizeof(s2));            scanf("%s",s1);            scanf("%s",s2);            int len1=strlen(s1);            int len2=strlen(s2);            int ans=len1+len2;            int x=kmp(s1,s2,len1,len2);            int y=kmp(s2,s1,len2,len1);            if(x>y)            {                printf("%d\n",ans-x);            }            else            {                printf("%d\n",ans-y);            }        }    }}