Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.
A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.
Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.
Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened.
You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
Input
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
Output
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
Examples
Input
fixprefixsuffix
Output
fix
Input
abcdabc
Output
Just a legend
题意:给定一个字符串,求他的最长的子串,使得其同时是原字符串的前缀、后缀,并且去原字符串掉第一个和最后一个字母后,该子串仍然存在。无解输出“Just a legend”。
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<queue>
#include<cmath>
#include<stack>
#include <map>
#include <queue>
using namespace std;
typedef unsigned long long ull;
const int m = 10000010;
const int p = 163;
char mapp[m];
ull hashh[m], idx[m];
int n, flag[m];
int main()
{
while(scanf("%s", mapp+1)!=EOF)
{
//hash的常规操作;
int len = strlen(mapp+1);
idx[0] = 1;
hashh[0] = 0;
for(int i=1; i<=len; i++)
{
idx[i] = idx[i-1]*p;
hashh[i] = hashh[i-1]*p+mapp[i];
}
flag[1] = flag[2] = 1;
//flag[i]数组用来记录在第i个字符前除去与其相同的后缀外,存在第二个的 最长子串的长度;
for(int i=2; i<=len; i++)
{
int j = flag[i];
while(j>1&&mapp[i]!=mapp[j])
j = flag[j];
if(mapp[i]== mapp[j])
flag[i+1]=j+1;
else
flag[i+1]=1;
}
int p = 0;
for(int i=1; i<=len; i++)
{
int l = flag[i]-1;
//判断该字符串是否还存在(在除去相同后缀外),并且判断是否有相同的后缀;
if(l>p && hashh[l]==hashh[len]-hashh[len-l]*idx[l])
p = l;
}
if(p>0)
{
mapp[p+1] = '\0';
printf("%s\n", mapp+1);
}
else
printf("Just a legend\n");
}
return 0;
}