Simpsons’ Hidden Talents(HDU-2594)
题面
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 consists of two lines. The first line contains s1 and the second line contains s2. You may assume all letters are in lowercase.
输出
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.
样例输入
1clinton
2homer
3riemann
4marjorie
样例输出
10
2rie 3
提示
无
思路
求最长的相等的S的前缀与T的后缀。将S和T拼接起来,求next数组即可,注意答案与原长求min。
代码
1char s[mxn], t[mxn];
2int nxt[mxn];
3
4void getnxt(char* t, int m)
5{
6 int i = 0, j = -1; nxt[0] = -1;
7 while (i < m)
8 {
9 if (j == -1 || t[i] == t[j]) {
10 i++, j++;
11 // if (t[i] == t[j])
12 // nxt[i] = nxt[j]; // next数组优化
13 // else
14 nxt[i] = j;
15 } else
16 j = nxt[j];
17 }
18}
19
20int main()
21{
22 while(~scanf("%s %s", s, t))
23 {
24 int n = strlen(s), m = strlen(t);
25 strcpy(s+n, t);
26 getnxt(s, n+m);
27 int ans = min(nxt[n+m], min(n, m));
28 if(ans)
29 printf("%s ", s+n+m-ans);
30 printf("%d\n", ans);
31 }
32 return 0;
33}