【题解】HDU-2594 Simpsons’ Hidden Talents

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.

样例输入

1
2
3
4
clinton
homer
riemann
marjorie

样例输出

1
2
0
rie 3

提示

思路

求最长的相等的S的前缀与T的后缀。将S和T拼接起来,求next数组即可,注意答案与原长求min。

代码

查看代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
char s[mxn], t[mxn];
int nxt[mxn];

void getnxt(char* t, int m)
{
int i = 0, j = -1; nxt[0] = -1;
while (i < m)
{
if (j == -1 || t[i] == t[j]) {
i++, j++;
// if (t[i] == t[j])
// nxt[i] = nxt[j]; // next数组优化
// else
nxt[i] = j;
} else
j = nxt[j];
}
}

int main()
{
while(~scanf("%s %s", s, t))
{
int n = strlen(s), m = strlen(t);
strcpy(s+n, t);
getnxt(s, n+m);
int ans = min(nxt[n+m], min(n, m));
if(ans)
printf("%s ", s+n+m-ans);
printf("%d\n", ans);
}
return 0;
}
_/_/_/_/_/ EOF _/_/_/_/_/