zoukankan      html  css  js  c++  java
  • 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.

    InputThe 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.
    OutputFor 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

     1 #include<cstdio>
     2 #include<iostream>
     3 #include<cstring>
     4 using namespace std;
     5 const int maxn=1e6+5;
     6 const int mod = 1e4+7;
     7 int net[maxn],len;
     8 char c[maxn];
     9 void getnext(){
    10     int l = strlen(c);
    11     int i = 0,j = -1;
    12     net[0]=-1;
    13     while(i<l){
    14         if(j==-1||c[i]==c[j]) net[++i]=++j;
    15         else j = net[j];
    16     }
    17 }
    18 int main()
    19 {
    20     int t;
    21     cin>>t;
    22     while(t--){
    23         cin>>len>>c;
    24         getnext();
    25         int l = strlen(c),res = 0;
    26         for(int i = 0;i < l;++i){
    27             if(net[i]!=0&&net[i]+1!=net[i+1])res += net[i];
    28         }
    29         cout<<(res+l+net[l])%mod<<endl;
    30     }
    31     return 0;
    32 }
  • 相关阅读:
    字符串的比较方法---Java
    [模板]二进制枚举
    [唯一分解定理]感谢ZLY讲解
    [数学] 小数点后第n位
    [模板]二维前缀和
    [模板]欧拉函数及其应用
    [51nod] 1024 矩阵中不重复的元素
    Codeforces Round #521 (Div. 3) D. Cutting Out
    [差分] [POJ] 3276 Face The Right Way
    Educational Codeforces Round 54 (Rated for Div. 2) C. Meme Problem
  • 原文地址:https://www.cnblogs.com/h404nofound/p/11704057.html
Copyright © 2011-2022 走看看