• HDU 3336 Count the string (求前缀在字符串中出现的次数和)


    Count the string

    Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)

    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
    /*
     * HDU 3336 Count the string
     * 求前缀在字符串中出现的次数和
     *
     * KMP+dp
     * 问题可以转化为,求以i结尾的字符串所包含的前缀的个数
     * 定义状态dp[i]表示前缀i所包含的前缀的个数,考虑转移,借助KMP的next数组
     * 前缀i所包含的最长的前缀的长度为next[i],在next[i]+1~i之间的前缀没有
     * 故dp[i]=dp[next[i]]+1,递推即可
     */
    
    #include <stdio.h>
    #include <string.h>
    #include <iostream>
    using namespace std;
    
    const int MAXN = 200000+10;
    const int MOD = 10007;
    
    void Get_Next(char* P,int* next)
    {
        int i=0,k=-1;
        int plen=strlen(P);
        next[0]=-1;
        while(i<plen)
        {
            if(k==-1||P[k]==P[i])
            {
                i++,k++;
                next[i]=k;
            }
            else k=next[k];
        }
    }
    char str[MAXN];
    int nxt[MAXN];
    int dp[MAXN];
    
    int main()
    {
        int T;
        int n;
        scanf("%d",&T);
        while(T--)
        {
            int ans;
            scanf("%d%s",&n,str);
            Get_Next(str,nxt);
            dp[0]=0;
            for(int i=1;i<=n;i++)
            {
                dp[i]=dp[nxt[i]]+1;
                dp[i]%=MOD;
                ans+=dp[i];
                ans%=MOD;
            }
            printf("%d
    ",ans);
        }
        return 0;
    }
  • 相关阅读:
    php redis 操作大全
    迟到的2017读书计划
    将博客搬至CSDN
    maven安装教程
    liunx centOS6.5安装jdk教程
    centOS6.0虚拟机ip配置
    html网页调用本地exe程序的实现方法:
    org.springframework.beans.factory.BeanCreationException 解决异常错误
    sqlserver查看锁表进程及对锁定的表进行解锁
    tomcat免安装版做成windows系统服务
  • 原文地址:https://www.cnblogs.com/wangdongkai/p/5799885.html
Copyright © 2020-2023  润新知