It seems to have seen in a dream the way

https://loj.ac/problem/10047

Title Description

  Given a string \ (S \) , which is determined to satisfy the substring \ (the ABA \) form and \ (| A | ≧ K \) , \ (| ≧ 1 \ | B) number.

Thinking

  This question is first of all clear \ (n ^ 2 \) violence can be treated, but can be converted to the title defined \ (A \) is a substring of a length greater than the common prefix and suffix \ (K \) , less than an entire substring length \ (\ FRAC. 1} {2} {\) , we consider \ (the KMP \) to seek a common prefix and suffix, and then judgment can be violent. But taking into account each time the judge to continue to jump ahead, there is the possibility of overtime, we consider optimization. First, we enumerate the left end of each string, apparently to enumerate \ (nk * 2 \) on it. Next, for the \ (l \ sim n \) this period once \ (the KMP \) . For \ (S [l ... r] \) this section, we consider the process out \ (P [I] = J \) , then if \ (J <K-L. 1 + \) , then the longest common the prefix and suffix is not satisfied, \ (G [I] = I \) , i.e. only this period entirety \ (A \) string; otherwise satisfy the condition, with regard to \ (g [j] \) condition, because we want to make it as short as possible, so little influence on subsequent state. The last recorded position as long as the answer to the judgment of whether this section of the middle position.

Code

#include <bits/stdc++.h>
using namespace std;
const int MAXN=2e4+10;
char s[MAXN];
int pre[MAXN],n,g[MAXN];
int main() 
{
    int k;
    scanf(" %s",s+1);
    scanf("%d",&k);
    n=strlen(s+1);
    int ans=0;
    for(int l=1;l<=n-(k<<1);l++)
    {
        pre[l]=l-1;
        int j=l-1;
        g[l]=l;
        for(int p=l;p<n;p++)
        {
            while(j>l-1&&s[p+1]!=s[j+1])j=pre[j];
            if(s[p+1]==s[j+1])j++;
            pre[p+1]=j;
            g[p+1]=(j<l+k-1)?p+1:g[j];
            if(g[p+1]<(l+p+1)/2)
                ans++;
        }
    }
    printf("%d",ans);
    return 0;
}

Guess you like

Origin www.cnblogs.com/fangbozhen/p/11788215.html