zoukankan      html  css  js  c++  java
  • HDU 3336 Count the string KMP

                                                               Count the string

     

    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

       代码:

    // 本题是让我们认识f 数组的含义
    
    #include<cstdio>
    #include<iostream>
    #include<cstring>
    #define M 200010
    using namespace std ;
    char p[M] ;
    int f[M] , dp[M] ;
    int n , ans ;
    void get()
    {
        int i , j = -1 ;
        f[0] = -1 ;dp[0] = 1 ;
        for(i = 1 ;i < n ;i++){
            if( j >= 0 && p[j+1] != p[i]) j = f[j] ;
            if( p[j+1] == p[i] ) j++ ;
            if( j >= 0 ) dp[i] = ( dp[j] + 1 ) % 10007 ;
            else dp[i] = 1 ;
            f[i] = j ;
            ans = ( ans + dp[i] ) % 10007 ;
        }  
    }
    int main()
    {
        int i , T ;
        cin >> T ;
        while( T-- ){
            cin >> n ;
            cin >> p ;
            memset( dp , 0 , sizeof(dp)) ;    
            ans = 1 ;
            get( ) ;
            cout << ans << endl ;
        }
    }

                                            

  • 相关阅读:
    c++——类 继承
    Pytorch Tensor, Variable, 自动求导
    Python-OpenCV实现二值图像孔洞填充
    神经网络手写数字识别numpy实现
    神经网络反向传播公式推导
    转:Markdown语法大全
    markdown居中对齐,左对齐,右对齐
    硬编码与软编码
    转:Markdown数学公式语法
    Python if __name__=='__main__'
  • 原文地址:https://www.cnblogs.com/20120125llcai/p/3039002.html
Copyright © 2011-2022 走看看