zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    华为笔试
    进程间通信——管道通信
    进程间通信——使用WM_COPYDATA消息通信
    混合高斯背景建模
    基于mean shift的目标跟踪算法
    Lukas-Kanade光流法
    【CUDA并行编程之八】Cuda实现Kmeans算法
    【CUDA并行编程之七】数组元素之和
    【CUDA并行编程之六】KNN算法的并行实现
    【CUDA并行编程之五】计算向量的欧式距离
  • 原文地址:https://www.cnblogs.com/wangdongkai/p/5799885.html
Copyright © 2011-2022 走看看