UOJ Logo SHYI的博客

博客

【NOI2016】优秀的拆分 题解(95分)

2016-08-02 10:21:49 By SHYI

题目大意:求一个字符串中形如AABB的子串个数。

思路:用哈希做到O(1)判断字符串是否相同,O($n^2$)预处理,ans[i]为开头位置为i的形如AA的子串个数。再用O($n^2$)枚举出AABB中的AA,加上BB(已预处理)的个数即可。时间复杂度为O($n^2$),最后一个点过不掉~~。(此方法为在下所想的朴素算法,比不得大神们的方法,代码更是烂得要死)

代码:

#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
const int S=999983,mod=100000009;
char s[40000];
long long ans[40000],Hash[40000],mi[40000];

int gethash(int l,int r)
{
    return (Hash[r]-Hash[l-1]*mi[r-l+1]%mod+mod)%mod;
}

int main()
{
    int n;
    scanf("%d",&n);
    while (n--)
    {
        int cnt,i,j;
        long long sum=0;
        scanf("%s",s+1); cnt=strlen(s+1);
        for (i=1;i<=cnt;i++) Hash[i]=(Hash[i-1]*S+s[i]-'a'+1)%mod;
        for (mi[0]=i=1;i<=cnt;i++) mi[i]=mi[i-1]*S%mod;
        for (i=1;i<=cnt;i++) ans[i]=0;
        for (i=1;i<=cnt;i++)
            for (j=i;j+j-i+1<=cnt;j++)
                if (gethash(i,j)==gethash(j+1,j+j-i+1)) ans[i]++;
        for (i=2;i<cnt-1;i++)
            for (j=i;j>i+1>>1;j--)
                if (gethash(j,i)==gethash(j-i+j-1,j-1)) sum+=ans[i+1];
        printf("%d\n",sum);
    }
    return 0;
}

评论

暂无评论

发表评论

可以用@mike来提到mike这个用户,mike会被高亮显示。如果你真的想打“@”这个字符,请用“@@”。