HDU 3336 Next数组小核心/拓展KMP

Count the string

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 13320    Accepted Submission(s): 6098


Problem Description
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.
 

Input
The first line is a single integer T, indicating the number of test cases.
For each case, the first line is an integer n (1 <= n <= 200000), which is the length of string s. A line follows giving the string s. The characters in the strings are all lower-case letters.
 

Output
For each case, output only one number: the sum of the match times for all the prefixes of s mod 10007.
 

Sample Input
 
  
1 4 abab
 

Sample Output
 
  
6
 

Author
foreverlin@HNU
 

Source
 

Recommend

lcy   |   We have carefully selected several similar problems for you:  3341 2222 3068 3339 3337 


这题啊 就知道了一个结论 求abab里a,ab,aba,abab的次数问题 可以对自身跑一遍拓展KMP 那么把EXNEXT相加也就是所求的答案 或者跑一次Next只要Next不是0就加加

这个结论 给出来

给个小证明

比如  abab Next数组分别是0 0 1 2

我们这样分析 你竟然Next是字符串最长前缀和相同后缀那么我Next存在 就是对这长前缀后缀要进行+1,至于为啥不加2?因为你q从前面1开始 那么对这个前缀 一定有他本身相加 比如abab Next[4]=2 也就是ab=ab,但是在q=2的时候 Next[2]=0,我们加了一次 加的其实就是这个ab

所以后面加加 为啥要进行q=Next[q]?对 你聪明的 我们从这个长前缀后缀找里面小的前缀后缀 那么是不是我们只要对这个小后缀进行一次++,同理小前缀加过了 如果Next[]是0 代表就是它自己本身匹配了一下

所以答案就出来了

拓展KMP也就是进行了一次这个过程

不过KMPNext也可以直接判断

时间复杂度应该相差无几

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <cmath>
using namespace std;
#define dbg(x) cout<<#x<<" = "<< (x)<< endl
const int MAX_N = 1000024;
int Next[MAX_N];
string str;
int n1,n2;
void getnext(string str){
    int i = 0,j=-1;
    while(i<n2){
    if(j==-1||str[i]==str[j]) {++i,++j,Next[i]=j;}
    else j=Next[j];
    }
    return ;
}

int main(){
    int t ,cnt;
    ios::sync_with_stdio(false);
    cin >> t;
    while(t--){
        //memset(Next,0,sizeof(Next));
        cnt = 0;
        cin>>n1;
        cin>>str;
        n2=n1;
        Next[0]=-1;
        getnext(str);
        //printf("%s\n",str.c_str())
        for(int i=1;i<=n1;i++){
            int q =i;
            while(q!=0){
            cnt++;
            cnt%=10007;
            q=Next[q];
            }
        }
        cout << cnt%10007 << endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/heucodesong/article/details/80999596