HDU1867 A + B for you again KMP

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

#include <iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
using namespace std;
const int MAXN=100000+1000;
char *S,*T;
char str1[MAXN],str2[MAXN];
int next[MAXN];
int n,m;
void getFail(char *T)
{
    next[0]=next[1]=0;
    for(int i=1;i<m;i++)
    {
        int j=next[i];
        while(j && T[i]!=T[j]) j=next[j];
        next[i+1] = (T[i]==T[j])?j+1:0;
    }
}
int KMP(char *S,char *T)
{
    int j=0;
    n=strlen(S);
    m=strlen(T);
    getFail(T);
    for(int i=0;i<n;i++)
    {
        while(j && S[i]!=T[j]) j=next[j];
        if(S[i]==T[j]) j++;//j是匹配的长度
        if(i==n-1) return j;
    }
/*
next数组里面存放的是要查找的字符串前i个字符串的所有前缀、后缀相等的公共串中,最大的长度值。比如需要查找的一个子串ababcd,next[0]表示子串中前1个字符串即a的前缀和后缀中相等字符串的最大长度,因为a的前缀和后缀没有,故next[0] = 0;对于next[2],即先求出子串aba的前缀和后缀出来,前缀为a,ab,后缀有ba,a,相等的公共串为a,长度为1,因此next[2] = 1;依次可以求出。
*/
}
int main()
{
    while(scanf("%s%s",str1,str2)==2)
    {
        int len1=KMP(str1,str2);//把str2当做目标串;
        int len2=KMP(str2,str1);//
        if(len1==len2)
        {//左右相同,len1返回匹配的位置例如asdf sdfgh就返回匹配长度
            if(strcmp(str1,str2)<0)
            {
                printf("%s",str1);//str1小放前面
                printf("%s\n",str2+len1);//把匹配的长度当做输出str2开始的位置
            }
            else
            {
                printf("%s",str2);
                printf("%s\n",str1+len2);
            }
        }
        else if(len1<len2)
        {
            printf("%s",str2);
            printf("%s\n",str1+len2);
        }
        else
        {
            printf("%s",str1);
            printf("%s\n",str2+len1);
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/lanshan1111/article/details/84867103