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

                                            

  • 相关阅读:
    超强问卷调查系统源码购买及二次开发
    asp.net core mvc上传大文件解决方案
    asp.net core mvc发布后显示异常错误信息的方法
    基于.net core 2.0+mysql+AceAdmin搭建一套快速开发框架
    改造kindeditor支持asp.net core mvc上传文件
    Centos7 Nginx安装使用
    Centos7 守护进程supervisord 安装使用
    Centos7 .net core 2.0安装使用
    Centos7 Mysql安装
    Centos7 Redis安装
  • 原文地址:https://www.cnblogs.com/20120125llcai/p/3039002.html
Copyright © 2020-2023  润新知