您的位置:首页 > 大数据 > 人工智能

KMP——HDU 1867 A + B for you again

2017-02-06 12:21 190 查看
额,这里是一些细节容易错。

1.母串和子串是不定的,不一定母串是前面一个

2.当母串和子串相等的时候

代码

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
#define maxn 100005
char s[maxn];
char p[maxn];
int next1[maxn];
void GetNext(char *p)
{
memset(next1,0,sizeof(next1));
int plen=strlen(p);
next1[0]=-1;
int k=-1;
int j=0;
while(j<plen-1)
{
if(k==-1||p[j]==p[k])
{
k++;
j++;
next1[j]=k;
}
else
k=next1[k];
}
}
int Kmpsearch(char *s,char *p)
{
GetNext(p);
int i=0,j=0;
int slen=strlen(s);
int plen=strlen(p);
while(i<slen)
{
if(j==plen)
j=next1[j];
if(j==-1||s[i]==p[j])
{
i++;
j++;
}
else
j=next1[j];
}
return j;//这里返回的是相同的数量
}
int main()
{
while(scanf("%s %s",s,p)!=EOF)
{
int h1=0,h2=0,g=0;
h1=Kmpsearch(s,p);
h2=Kmpsearch(p,s);
if(h1>h2)
cout<<s<<p+h1<<endl;//p+h1
else if(h1<h2)
cout<<p<<s+h2<<endl;
else
{
if(strcmp(s,p)<=0)//这里
cout<<s<<p+h1<<endl;
else
cout<<p<<s+h2<<endl;
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: