HDU 1867 A+B for you again

这道题的意思就是找出一个最大的公共子串,这个子串是一个字符串的尾串(tail substring ),同时是另外那个字符串的头串(head substring),是满足A+B的长度strlen(A+B)达到最小值,这里面要注意的一个问题是,谁做模式串P是不一定的,所以要分别比较不同字符串作为模式的KMP值。

这里用到KMP匹配算法里面的next函数,KMP返回的就是那个公共子串的长度。

View Code
 1 #include <iostream>
2 #include<stdio.h>
3 #include<string.h>
4 #include<string>
5 using namespace std;
6 int next[100010];
7 void getNext(char P[])
8 {
9 int j=0,k=-1;
10 next[0]=-1;
11 int lenP=strlen(P);
12 while(j<lenP)
13 {
14 if(k==-1 || P[j]==P[k])
15 {
16 k++;j++;
17 next[j]=k;
18 }
19 else
20 k=next[k];
21 }
22 }
23 int KMP(char T[],char P[])
24 {
25 memset(next,0,sizeof(next));
26 getNext(P);
27 int posP=0,posT=0;
28 int lenT=strlen(T);
29 while(posT<lenT)
30 {
31 if(posP==-1 || P[posP]==T[posT])
32 {
33 posP++;posT++;
34 }
35 else
36 posP=next[posP];
37 }
38 return posP;
39 }
40 char S1[100005],S2[100005];
41 int main()
42 {
43 while(scanf("%s %s",S1,S2)!=EOF)
44 {
45 int len1=KMP(S1,S2);
46 int len2=KMP(S2,S1);
47 if(len1==len2)
48 {
49 if(strcmp(S1,S2)<0)
50 {
51 printf("%s%s\n",S1,S2+len1);
52 }
53 else
54 {
55 printf("%s%s\n",S2,S1+len1);
56 }
57 }
58 else
59 if(len1<len2)
60 {
61 printf("%s%s\n",S2,S1+len2);
62 }
63 else
64 printf("%s%s\n",S1,S2+len1);
65 }
66 return 0;
67 }

posted on 2011-09-15 22:48  lonelycatcher  阅读(512)  评论(0编辑  收藏  举报

导航