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.
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.
The lengths of s1 and s2 will be at most 50000.
clinton homer riemann marjorie
0 rie 3
题解:
给你两个串,问你是否存在其中一个的前缀等于另一个的后缀,有就输出最长的前缀字符串,和长度
思路:
这题很好想,是我第一次没看题解就a的KMP题,直接将两个字符串连接起来求next数组,如果next[len]大于了其中任何一个字符串就输出小的就行了,如果小于就看next是否为0,不为0就输出0到next[len]的字符
代码:
#include<algorithm>
#include<iostream>
#include<cstring>
#include<stdio.h>
#include<math.h>
#include<string>
#include<stdio.h>
#include<queue>
#include<stack>
#include<map>
#include<vector>
#include<deque>
using namespace std;
#define lson k*2
#define rson k*2+1
#define M (t[k].l+t[k].r)/2
#define INF 1008611111
#define ll long long
#define eps 1e-15
char T[100005];
int Next[100005];
void init()
{
int i=0,j=-1;
Next[0]=-1;
while(T[i])
{
if(j==-1||T[j]==T[i])
{
i++;
j++;
Next[i]=j;
}
else
j=Next[j];
}
}
int main()
{
char s1[50005],s2[50005];
int i,j,len1,len2,len;
while(scanf("%s%s",s1,s2)!=EOF)
{
len1=strlen(s1);
len2=strlen(s2);
for(i=0;i<len1;i++)
T[i]=s1[i];
for(j=0;j<len2;j++,i++)
T[i]=s2[j];
T[i]='\0';
len=i;
init();
if(Next[len]>min(len1,len2))
{
if(len1<len2)
{
printf("%s %d\n",s1,len1);
}
else
printf("%s %d\n",s2,len2);
}
else
{
if(Next[len])
{
for(i=0;i<Next[len];i++)
printf("%c",s1[i]);
printf(" %d\n",Next[len]);
}
else
printf("0\n");
}
}
return 0;
}