kuangbin专题十六 KMP&&扩展KMP HDU2594 Simpsons’ Hidden Talents

Homer: Marge, I just figured out a way to discover some of the talents we weren’t aware we had.
Marge: Yeah, what is it?
Homer: Take me for example. I want to find out if I have a talent in politics, OK?
Marge: OK.
Homer: So I take some politician’s name, say Clinton, and try to find the length of the longest prefix
in Clinton’s name that is a suffix in my name. That’s how close I am to being a politician like Clinton
Marge: Why on earth choose the longest prefix that is a suffix???
Homer: Well, our talents are deeply hidden within ourselves, Marge.
Marge: So how close are you?
Homer: 0!
Marge: I’m not surprised.
Homer: But you know, you must have some real math talent hidden deep in you.
Marge: How come?
Homer: Riemann and Marjorie gives 3!!!
Marge: Who the heck is Riemann?
Homer: Never mind.
Write a program that, when given strings s1 and s2, finds the longest prefix of s1 that is a suffix of s2.

InputInput consists of two lines. The first line contains s1 and the second line contains s2. You may assume all letters are in lowercase.OutputOutput consists of a single line that contains the longest string that is a prefix of s1 and a suffix of s2, followed by the length of that prefix. If the longest such string is the empty string, then the output should be 0.
The lengths of s1 and s2 will be at most 50000.Sample Input
clinton
homer
riemann
marjorie
Sample Output
0
rie 3


思路就是直接拼接,然后处理即可。刚开始什么都没考虑,直接交了。后来一点点发现了问题。8Y

列举几个特殊样例即可

ab
abab

abab
ab

abc
ab

ab
cabc

len1为s1的长度,len2为s2的长度,len为总长

可以发现如果Next[len]<==0 肯定为0

否则可能为0

就是循环节的长度大于s1 或者满足了不大于s1但是最终长度大于s2

还有可能就是一个很短的循环节循环了好多次。


 1 #include<stdio.h>
 2 #include<string.h>
 3 char s[100010],s1[50010];
 4 int len,lentemp1,lentemp2,Next[100010];
 5 
 6 void prekmp() {
 7     int i,j;
 8     j=Next[0]=-1;
 9     i=0;
10     while(i<len) {
11         while(j!=-1&&s[i]!=s[j]) j=Next[j];
12         Next[++i]=++j;
13     }
14 }
15 
16 int main() {
17     //freopen("in","r",stdin);
18     while(~scanf("%s",s)) {
19         lentemp1=strlen(s);
20         scanf("%s",s1);
21         lentemp2=strlen(s1);
22         strcat(s,s1);
23         len=strlen(s);
24         prekmp();
25         if(Next[len]>0) {
26             int i=Next[len];
27             while(i>lentemp1||i>lentemp2) {//小于s1&&小于s2  找满足条件的最大i
28                 i=Next[i];
29             }
30             if(i<=0) printf("0\n");
31             else {
32                 for(int j=0;j<i;j++) printf("%c",s[j]);
33                 printf(" %d\n",i);
34             }
35         } else printf("0\n");
36     }
37 }

 








posted @ 2019-01-14 21:18  Frontierone  阅读(126)  评论(0编辑  收藏  举报