3620: 似乎在梦中见过的样子 KMP

枚举左端点跑KMP, O(n2) 也能过真是!@#¥%……

#include
#include
#include
using namespace std;
int n,ans,k;
char s[20005];
int next[20005];
inline void KMP(int p)
{
    for (int i=1;i<=n;i++)
        next[i]=p-1;
    int j=p-1;
    for (int i=p+1;i<=n;i++)
    {
        while (j!=p-1&&s[j+1]!=s[i]) j=next[j];
        if (s[j+1]==s[i]) j++;
        next[i]=j;
    }
    j=p-1;
    for (int i=p+1;i<=n;i++)
    {
        while (j!=p-1&&s[j+1]!=s[i]) j=next[j];
        if (s[j+1]==s[i]) j++;
        while ((j-p+1)*2>=(i-p+1)) j=next[j];
        if (j-p+1>=k) ans++;
    }
}
int main()
{
    scanf("%s%d",s+1,&k);
    n=strlen(s+1);
    for (int i=1;i<=n;i++)
        KMP(i);
    cout << ans << endl;
}

你可能感兴趣的:(My,Code)