• hdu 3336 Count the string


    Count the string

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


    Problem 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
     
    题目大意:
         计算输入的字符串的所有前缀在串中出现的次数。比如字符串abab,a出现2次,ab出现2次,aba出现1次,abab出现1次。
     
    解题思路:
         KMP算法,next数组的使用
         对KMP不太熟悉的可以看这里:从头到尾理解KMP算法
     
     
     1 #include <stdio.h>
     2 #include <string.h>
     3 
     4 char s[200100];
     5 int next_[200100],n;
     6 void getnext()
     7 {
     8     int i = 0, j = -1;
     9     next_[0] = -1;
    10     while (i < n){
    11         if (j == -1 || s[i] == s[j])
    12             next_[++ i] = ++ j;
    13         else
    14             j = next_[j];
    15     }
    16 }
    17 int main()
    18 {
    19     int i,t,sum;
    20     scanf("%d",&t);
    21     while (t --)
    22     {
    23         scanf("%d",&n);
    24         scanf("%s",s);
    25         getnext();
    26         sum = n;   // 首先可以确定的数量为n(每一个长度的前缀) 
    27         for (i = 1; i <= n; i ++)
    28         {
    29             if (next_[i] > 0) sum ++;  // next[i]不等于0 说明此位置出现与前缀相同的子串 
    30             sum %= 10007;
    31         }
    32         printf("%d
    ",sum);
    33     }
    34     return 0;
    35 }
         
  • 相关阅读:
    C#實現列舉DB中所有StoredProcedur
    Configure the browserJMeter
    DB 字段
    SQL Server 角色類型
    將N行數據合併成一行顯示
    性能计数器
    一千萬條以上記錄分頁數據庫優化
    SPFA静态链表优化+队列储存
    多源最短路pku1125
    图的连通性——folyd检验
  • 原文地址:https://www.cnblogs.com/yoke/p/6920651.html
Copyright © 2020-2023  润新知