标签:
HDU 2594 Simpsons’ Hidden Talents(辛普森一家的潜在天赋)
Time Limit: 2000/1000 MS (Java/Others)
Memory Limit: 32768/32768 K (Java/Others)
【Description】 |
【题目描述】 |
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. |
霍默: 玛姬, 我突然想到有个办法可以发掘我们的潜力。 玛姬: 厄, 那是啥? 霍默: 比如我想知道自己是否有潜力蹚官场... 玛姬: 恩。 霍默: 因此我列了写政客的名字,比如Clinton,然后找到他名字的前缀与我名字后缀相匹配的最大长度。这表示我有多大的希望成为和Clinton一样的政客。 玛姬: 那么究竟为什么比对最长前缀后缀??? 霍默: 毕竟大家都是真人不露相,玛姬。 玛姬: 那你的结果呢? 霍默: 0! 玛姬: 意料之中。 Homer: 但我知道,你肯定有潜在的数学天赋。 玛姬: 哪来的? 霍默: Riemann 和 Marjorie 匹配了 3!!! 玛姬: 黎曼是谁? 霍默: 不懂。
敲一个程序,对于给定的字符串s1与 s2,找出s1前缀与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. |
输入有两行。第一行是s1,第二行是s2。你可以认为只有小写字母。 |
【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. |
输出一行,包括最长s1前缀与s2后缀匹配的字符串,并输出前缀的长度。如果字符串不存在,输出0即可。 s1与s2的长度小于50000。 |
【Sample Input - 输入样例】 |
【Sample Output - 输出样例】 |
clinton homer riemann marjorie |
0 rie 3 |
【题解】
KMP比较部分的变形,利用next数组前移s1,匹配s2的时候为保存最后的匹配长度即可。
【代码 C++】
1 #include<cstdio> 2 #include<cstring> 3 #define mx 50005 4 char s1[mx], s2[mx]; 5 int nextS1[mx], optS2[mx], s1ED, s2ED; 6 void rdy(){ 7 int i = 0, j; 8 nextS1[0] = j = -1; 9 while (i < s1ED){ 10 if (j == -1 || s1[i] == s1[j]) nextS1[++i] = ++j; 11 else j = -1; 12 } 13 } 14 int count(){ 15 int i = 0, j = 0; 16 while (i < s2ED){ 17 if (j == -1 || s2[i] == s1[j]) optS2[++i] = ++j; 18 else j = nextS1[j]; 19 } 20 return optS2[s2ED]; 21 } 22 int main(){ 23 int len, i; 24 while (~scanf("%s%s", s1, s2)){ 25 s1ED = strlen(s1); s2ED = strlen(s2); 26 rdy(); 27 if (len = count()){ 28 for (i = 0; i < len; putchar(s1[i++])); 29 printf(" %d\n", len); 30 } 31 else puts("0"); 32 } 33 return 0; 34 }
HDU 2594 Simpsons’ Hidden Talents(辛普森一家的潜在天赋)
标签:
原文地址:http://www.cnblogs.com/Simon-X/p/5665449.html