Title Link: http://acm.hdu.edu.cn/showproblem.php?pid=2594
Simpsons ' Hidden Talents
Time limit:2000/1000 MS (java/others) Memory limit:32768/32768 K (java/others)
Total submission (s): 7354 Accepted Submission (s): 2620
Problem Descriptionhomer:marge, I just figured out a-to discover some of the talents we weren ' t aware we had.
Marge:yeah, what's it?
Homer:take me for example. I want to find out if I had 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 the Clinton ' s name is a suffix in my name. That's how close I'm to being a politician like Clinton
Marge:why on Earth Choose the longest prefix a suffix???
Homer:well, our talents is deeply hidden within ourselves, Marge.
Marge:so How close is you?
homer:0!
Marge:i ' m not surprised.
Homer:but know, you must has some real math talent hidden deep in.
Marge:how come?
Homer:riemann and Marjorie gives 3!!!
Marge:who the heck is Riemann?
Homer:never mind.
Write a program this, when given strings S1 and S2, finds the longest prefix of S1, which is a suffix of s2. Inputinput consists of the lines. The first line contains S1 and the second line contains S2. Assume all letters is in lowercase. Outputoutput consists of a single line that contains the longest string which is a prefix of S1 and a suffix of S2, followe D by the length of the. prefix. If the longest such string is the empty string and then the output should be 0.
The lengths of S1 and S2 would be in most 50000. Sample Inputclintonhomer Riemannmarjorie Sample Output0rie 3Main topic: Enter two strings at a time s1,s2 and then find a string that satisfies both the S1 prefix and the S2 suffix if you can find the output of the string and its length otherwise output 0Problem Solving: KMP algorithm finds the next array of S1 and compares the S2 array with the S1 array
1#include <stdio.h>2#include <string.h>3 Chars1[50050],s2[50050];4 intnext[50050];5 voidGetNext ()6 {7 inti =0, j =-1;8next[0] = -1;9 intLen =strlen (S1);Ten while(I <len) One { A if(j = =-1|| S1[i] = =S1[j]) - { -i + +; theJ + +; - if(S1[i] = =S1[j]) -Next[i] =Next[j]; - Else +Next[i] =J; - } + Else Aj =Next[j]; at } - } - intKMP () - { - inti =0, j =0; - intLen1 =strlen (S1); in intLen2 =strlen (S2); - while(I < LEN2)//special attention to the template with a little difference to { + if(j = =-1|| S1[J] = =S2[i]) - { thei + +; *J + +; $ }Panax Notoginseng Else -j =Next[j]; the } + returnJ; A } the intMain () + { - while(~SCANF ("%s", S1)) $ { $scanf"%s", S2); - GetNext (); - intLen =KMP (); the - for(inti =0; i < Len; i + +)Wuyiprintf"%c", S1[i]); the if(len) -printf" "); Wuprintf"%d\n", Len); - } About return 0; $}
View Code
HDU 2594 Simpsons ' Hidden talents