您的位置:首页 > 其它

HDU 1867 KMP

2013-02-05 11:41 218 查看
题意:

求str1 的最长后缀与 str2 的最长前缀。使得 str1+str2 的长度最小,并且字典序最小(str1和str2可以互换)

题解:

kmp的p数组的含义:p[i]表示以i为结尾的字符串最多和开头匹配的个数。也正是这道题求解的关键、

具体做法就是将两个字符串合并处理求一下p数组就好了~

ps:合并的时候中间一定要加“分隔符”(比如:#,@之类的~),否则会有惊喜。。。

abcbcbca bcbcbc 对拍了半天才发现这个bug。。。

View Code

#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <algorithm>

#define N 2001000

using namespace std;

int lena,lenb,lenc;
int p
;
char str1
,str2
,c
;

inline void getp()
{
p[1]=0;
for(int i=2,len=0;i<=lenc;i++)
{
while(len>0&&c[i]!=c[len+1]) len=p[len];
if(c[i]==c[len+1]) len++;
p[i]=len;
}
}

inline int getlen(char a[],char b[])
{
lena=strlen(a+1);
lenb=strlen(b+1);
lenc=lena+lenb+1;
for(int i=1;i<=lenb;i++) c[i]=b[i];
c[1+lenb]='#';
for(int i=1;i<=lena;i++) c[i+lenb+1]=a[i];
getp();
return p[lenc];
}

inline void go()
{
int len1=getlen(str1,str2);
int len2=getlen(str2,str1);
if(len1==len2)
{
if(strcmp(str1+1,str2+1)<0) printf("%s%s",str1+1,str2+len1+1);
else printf("%s%s",str2+1,str1+len2+1);
}
else if(len1<len2) printf("%s%s",str2+1,str1+len2+1);
else printf("%s%s",str1+1,str2+len1+1);
puts("");
}

int main()
{
while(scanf("%s%s",str1+1,str2+1)!=EOF) go();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: