hdu3336 Count the string 扩展KMP

It is well known that AekdyCoin is good at string problems as well as number theory problems. When given a string s, we can write down all the non-empty prefixes of this string. For example:
s: "abab"
The prefixes are: "a", "ab", "aba", "abab"
For each prefix, we can count the times it matches in s. So we can see that prefix "a" matches twice, "ab" matches twice too, "aba" matches once, and "abab" matches once. Now you are asked to calculate the sum of the match times for all the prefixes. For "abab", it is 2 + 2 + 1 + 1 = 6.
The answer may be very large, so output the answer mod 10007.

题意:求一个字符串和它所有前缀的匹配次数总和,如'abab'与前缀'ab'匹配次数为2。

用扩展KMP与自身匹配。

 1 #include<stdio.h>
 2 #include<string.h>
 3 #include<algorithm>
 4 using namespace std;
 5 
 6 const int maxn=2e5+5;
 7 const int mod=1e4+7;
 8 
 9 char s[maxn];
10 int ext[maxn],nxt[maxn];
11 
12 void EKMP(char s[],char t[],int lens,int lent){
13     int i,j,p,l,k;
14     nxt[0]=lent;j=0;
15     while(j+1<lent&&t[j]==t[j+1])j++;
16     nxt[1]=j;
17     k=1;
18     for(i=2;i<lent;i++){
19         p=nxt[k]+k-1;
20         l=nxt[i-k];
21         if(i+l<p+1)nxt[i]=l;
22         else{
23             j=max(0,p-i+1);
24             while(i+j<lent&&t[i+j]==t[j])j++;
25             nxt[i]=j;
26             k=i;
27         }
28     }
29 
30     j=0;
31     while(j<lens&&j<lent&&s[j]==t[j])j++;
32     ext[0]=j;k=0;
33     for(i=1;i<lens;i++){
34         p=ext[k]+k-1;
35         l=nxt[i-k];
36         if(l+i<p+1)ext[i]=l;
37         else{
38             j=max(0,p-i+1);
39             while(i+j<lens&&j<lent&&s[i+j]==t[j])j++;
40             ext[i]=j;
41             k=i;
42         }
43     }
44 }
45 
46 int main(){
47     int T;
48     scanf("%d",&T);
49     while(T--){
50         int n;
51         scanf("%d%s",&n,s);
52         EKMP(s,s,n,n);
53         int cnt=0;
54         for(int i=0;i<n;++i){
55             cnt=(cnt+ext[i])%mod;
56         }
57         printf("%d\n",cnt);
58     }
59     return 0;
60 }
View Code

 

转载于:https://www.cnblogs.com/cenariusxz/p/6592548.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值