zoukankan      html  css  js  c++  java
  • hdu 3336 Count the string(next数组)

    题意:统计前缀在串中出现的次数

    思路:next数组,递推

    #include<iostream>
    #include<stdio.h>
    #include<string.h>
    using namespace std;
    
    #define MaxSize 200005
    #define Mod 10007
    
    char str[MaxSize];
    int _next[MaxSize];
    int dp[MaxSize];
    int len;
    
    void GetNext(char t[]){//求next数组
        int j,k;//,len;
        j=0;
        k=-1;
        _next[0]=-1;
        //len=strlen(t);
        while(j<len){
            if(k==-1||t[j]==t[k]){
                ++j;
                ++k;
                _next[j]=k;//此句可由优化替代
                /*优化(仅保证求KMPIndex时可用。谨慎使用。)
                if(t[j]!=t[k])next[j]=k;
                else next[j]=next[k];
                */
            }
            else k=_next[k];
        }
    }
    
    int main(){
        int t,i,ans;
        scanf("%d",&t);
        while(t--){
            scanf("%d%s",&len,str);
            GetNext(str);//求子串的next数组
            dp[0]=0;
            ans=0;
            for(i=1;i<=len;++i){
                dp[i]=dp[_next[i]]+1;
                dp[i]%=Mod;
                ans+=dp[i];
                ans%=Mod;
            }
            printf("%d
    ",ans);
        }
        return 0;
    }
    View Code
  • 相关阅读:
    1051 Wooden Sticks(贪心-3)
    97 等价交换(贪心-2)
    python文件操作
    python学习-day 2
    python学习-day 1
    Python 测试题目-1
    Python list和dict方法
    Python 字符串
    while循环语句
    Python if判断语句
  • 原文地址:https://www.cnblogs.com/gongpixin/p/4749007.html
Copyright © 2011-2022 走看看