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;
    }
  • 相关阅读:
    textRNN & textCNN的网络结构与代码实现!
    四步理解GloVe!(附代码实现)
    NLP系列文章:子词嵌入(fastText)的理解!(附代码)
    自然语言处理(NLP)的一般处理流程!
    强化学习(Reinforcement Learning)中的Q-Learning、DQN,面试看这篇就够了!
    迁移学习(Transfer),面试看这些就够了!(附代码)
    白话--长短期记忆(LSTM)的几个步骤,附代码!
    三步理解--门控循环单元(GRU),TensorFlow实现
    Django框架1——视图和URL配置
    os模块
  • 原文地址:https://www.cnblogs.com/wangdongkai/p/5799885.html
Copyright © 2011-2022 走看看