Codeforces 126B. Password (KMP,DP)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.