HDU - 3336 Count the string(扩展kmp)

题目链接

http://acm.hdu.edu.cn/showproblem.php?pid=3336

题意

给你一个字符串,求它的每一个前缀出现的次数。

思路

先扩展kmp得到next数组,该字符串的每一个后缀的next值的和就是答案。
因为对于一个后缀,它的next值表示的是它和该字符串的前缀的最大匹配长度,比如说如果next[i]为3,后缀为abcd,这个时候字符串的a,ab,abc前缀都出现了一次,所以ans+=3。

代码

#include<iostream>
#include<stdlib.h>
#include<stdio.h>
#include<cmath>
#include<map>
#include<algorithm>
#include<string>
#include<string.h>
#include<set>
#include<queue>
#include<stack>
#include<functional>
using std::pair;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> PII;
typedef pair<PII,int> PPI;
typedef pair<ll,int> PLI;
const double PI=acos(-1);
const int maxn = 2e5+10;
const int maxm = 1e6 + 10;
const int mod = 1e4+7;
const int INF = 0x3f3f3f3f;
using namespace std;
int nex[maxn],ex[maxn];
char t[maxn];
int n;
void getnext()
{
    int j=0,po=1,len=n;
    nex[0]=len;
    while(t[j]==t[j+1]&&j+1<len) j++;
    nex[1]=j;
    for(int i=2;i<len;i++)
    {
        if(nex[i-po]+i<nex[po]+po) nex[i]=nex[i-po];
        else
        {
            j=nex[po]+po-i;
            if(j<0) j=0;
            while(i+j<len&&t[j]==t[j+i]) j++;
            nex[i]=j;
            po=i;
        }
    }
}

int main()
{
   int tt;
   cin>>tt;
   while(tt--)
   {
        scanf("%d%s",&n,t);
        getnext();
        int res=0;
        for(int i=0;i<n;i++) res=(res+nex[i])%mod;
        printf("%d\n",res);
   }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值