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 ;
        }
    }

                                            

  • 相关阅读:
    Centos环境下部署游戏服务器-自动化
    Centos环境下部署游戏服务器-SVN
    Centos环境下部署游戏服务器-权限
    Centos环境下部署游戏服务器-Eclipse
    Centos环境下部署游戏服务器-编译
    Centos环境下部署游戏服务器-软件安装
    基本的Logstash 例子
    安装Logstash
    安装Logstash
    mysqldump --master-data
  • 原文地址:https://www.cnblogs.com/20120125llcai/p/3039002.html
Copyright © 2011-2022 走看看