Codeforces 126B. Password
Test instructions: A string that finds the longest substring T, which is both a prefix and a suffix, and also appears in the middle. Output T, just a legend if not present.
Idea: Using the KMP algorithm to process the next array, by the meaning of the next array can know I is the longest tail of the same prefix suffix. [ne[n-1],ne[ne[n-1]],ne[ne[ne[n-1]]] ... Are the possible solutions, and the length is reduced, in order to efficiently validate each other, it is necessary to preprocess how many substrings of the entire string are identical to the prefix. Use the DP idea, Cnt[next[i]]+=cnt[i], inverted update again, you can process the above information. Then the prefix of CNT large equals 3 is a feasible solution
Code:
#include <iostream> #include <cstdio> #include <algorithm> #include <string> #define DD (x) cout << #x << "=" <<x<< "" #define DE (x) cout<< #x << "=" <<x<< "\ n" #define PB Push_back#define mp Make_pair#define fi first#define se second#define lson l,m,rt<<1#define rson m+1,r,rt<<1 |1using namespace Std;typedef Long long ll;typedef long double ld;const int Maxn=1e6+10,mod=1e9+7,inf=0x3f3f3f3f;char s[m Axn];int ne[maxn],cnt[maxn];void init () {ne[0]=-1; for (int i=1;s[i];++i) {int j=ne[i-1]; while (s[j+1]!=s[i]&&j>=0) j=ne[j]; if (s[j+1]==s[i]) ne[i]=j+1; else Ne[i]=-1; }}int Main () {scanf ("%s", s); Init (); int N=strlen (s); for (int i=0;i<n;++i) cnt[i]=1; for (int i=n-1;i;--i) cnt[ne[i]]+=cnt[i]; For (int. I=ne[n-1];i!=-1;i=ne[i]) {if (cnt[i]>=3) {for (int j=0;j<=i;++j) printf ("%c", S[j]); return 0; }} printf ("Just a Legend"); return 0;}
Codeforces 126B. Password (KMP,DP)