1. 程式人生 > >HDU 2594 Simpsons’ Hidden Talents

HDU 2594 Simpsons’ Hidden Talents

mat must most min 解題思路 ann ogr amp when

題目:

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.

Input

Input consists of two lines. The first line contains s1 and the second line contains s2. You may assume all letters are in lowercase.

Output

Output 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
題意描述:
輸入兩個串s1和s2
計算並輸出s1串的前綴和s2的後綴的最長相似部分和它的長度
解題思路:
KMP模板題,不同在於讓KMP函數匹配過程中讓s1跑完,最後返回最相似度j即可。
代碼實現:
 1 #include<stdio.h>
 2 #include<string.h>
 3 char s1[50010],s2[50010];
 4 int kmp(char s[],char t[]);
 5 void get_next(char t[],int next[],int
l); 6 int main() 7 { 8 int i,j,k; 9 while(scanf("%s%s",s1,s2) != EOF) 10 { 11 if( (k=kmp(s2,s1)) > 0 )//加括號 12 { 13 for(i=0;i<k;i++) 14 printf("%c",s1[i]); 15 printf(" %d\n",k); 16 } 17 else 18 printf("0\n"); 19 } 20 return 0; 21 } 22 int kmp(char s[],char t[]) 23 { 24 int i,j,l1,l2; 25 l1=strlen(s); 26 l2=strlen(t); 27 int next[50010]; 28 get_next(t,next,l2); 29 i=0; 30 j=0; 31 while(i < l1) 32 { 33 if(j==-1 || s[i] == t[j]) 34 { 35 i++; 36 j++; 37 } 38 else 39 j=next[j]; 40 } 41 //printf("j=%d\n",j); 42 return j; 43 } 44 void get_next(char t[],int next[],int l) 45 { 46 int i,j; 47 i=0;j=-1; 48 next[0]=-1; 49 while( i < l) 50 { 51 if(j==-1 || t[i]==t[j]) 52 { 53 i++; 54 j++; 55 next[i]=j; 56 } 57 else 58 j=next[j]; 59 } 60 /*for(i=0;i<=l;i++) 61 printf("%d ",next[i]); 62 printf("\n");*/ 63 }

易錯分析:

1、註意直接使用函數返回值作為判斷時最好將其賦值給一個變量,避免重復調用

HDU 2594 Simpsons’ Hidden Talents