zoukankan      html  css  js  c++  java
  • 计算字符串问题

    问题:给你一个字符串,然后让你把所有的前缀给找出来,并把它们在字符串中的出现次数相加,输出这个和写出算法。

    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

    回答:主要考察KMP算法运用

    #include<cstdio>
    #include<cstring>
    int n,m;
    char b[200010];
    int p[200010];
    void get_p(){
        p[1]=0;
        int i,j=0;
        for(i=2;i<=m;i++){
            while(j>0&&b[j+1]!=b[i]) j=p[j];
            if(b[j+1]==b[i]) j+=1;
            p[i]=j;
        }
    }
    int dp[200010];//dp【i】:以string[i]结尾的子串总共含前缀的数量
    int main(){
        int t,i;
        scanf("%d",&t);
        while(t--){
            scanf("%d",&m);
            scanf("%s",b+1);
            get_p();printf("%d ",p[9]);
            dp[0]=0;
            int sum=0;
            for(i=1;i<=m;i++){
                 dp[i]=dp[p[i]]+1;
                 sum=(sum+dp[i])%10007;
            }
            printf("%d ",sum);
        }

       return 0;
    }

  • 相关阅读:
    1093 Count PAT's(25 分)
    1089 Insert or Merge(25 分)
    1088 Rational Arithmetic(20 分)
    1081 Rational Sum(20 分)
    1069 The Black Hole of Numbers(20 分)
    1059 Prime Factors(25 分)
    1050 String Subtraction (20)
    根据生日计算员工年龄
    动态获取当前日期和时间
    对计数结果进行4舍5入
  • 原文地址:https://www.cnblogs.com/benchao/p/4503104.html
Copyright © 2011-2022 走看看