J - Count the string-next回溯

 

J - Count the string

 HDU - 3336 

后缀ans+1,接着对next回溯一直到为0,相当于把子串里蕴含的前缀子串也找出来,举个例子:  
    s         a    b    a    b    a
    i          0    1    2    3    4   5
next[i]     -1   0    0    1    2   3

开始 ans=5
next[3] = 1,ans + 1 = 6,next[1] = 0
next[4] = 2,ans + 1 = 7,next[2] = 0
next[5] = 3,ans + 1 = 8,next[3] = 1,ans + 1 = 9(这里就表示在aba这个后缀里还蕴涵着一个前缀a)
所以最后答案是9

#include<bits/stdc++.h>
using namespace std;
#define maxn  300000
int n,nxt[maxn],ans,temp;
string str;
void getnext()
{
    int i=0,j=-1;
    nxt[0]=-1;
    while(i<n)
    {
        if(j==-1||str[i]==str[j])
        {
            i++;
            j++;
            nxt[i]=j;
        }
        else
            j=nxt[j];
    }
}
int main()
{
    ios::sync_with_stdio(false);
    int t;
    cin>>t;
    while(t--)
    {
        memset(nxt,0,sizeof(nxt));
        cin>>n>>str;
        ans=n;
        getnext();
        for(int i=1; i<=str.size(); i++)
        {
            temp=nxt[i];
            while(temp)
            {
                ans=(ans+1)%10007;
                temp=nxt[temp];
            }
        }
        cout<<ans<<endl;
    }
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值