HDU Count the string

在做这个题之前,有一个很有意思的点,举个例子:ababab这个字符串的next数组是-1 0 0 1 2 3。

但是在getnext函数中,对next进行赋值的部分是next[++i] = ++j,也就是说每一次进入循环的i和在此次循环中next[i]的i是相差1的。

所以就说在-1 0 0 1 2 3的后面还有一个针对整个字符串的next[len] = 4(len是字符串长度)。

这个4就是在对字符串进行循环节计算时要用到的。

比如这个题:

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

题目要求输入一个字符串,找到这个字符串每个子串(都是从第一个字母开始,如:a,ab,aba,abab)在母串中出现的次数。

从next数组中可以发现关于前缀数的规律,如果用dt[i]表示该字符串前i个字符中出现任意以第i个字符结尾的前缀的次数,它的递推式是 

dt[i]=d[next[i]]+1,

即以第i个字符结尾的前缀数等于以第next[i]个字符为结尾的前缀数加上它自己本身。

所以只要找到每个字符串的next数组,就可以轻松解决。(注意next【0】是用的,相当于用next【len】去代替next【0】)。

#include<iostream>
#include<cstdio>
#include<cstring>

using namespace std;

const int maxn=200010;
const int mod=10007;

int ne[maxn];
int dt[maxn];
char str[maxn];

void getnext(int len)
{
    int i=0,j=-1;
    ne[0]=-1;
    while(i<len)
    {
        if(j==-1 || str[i]==str[j])
        {
            ne[++i] = ++j;
        }
        else
            j=ne[j];
    }
}
int main()
{
    int t,n;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d",&n);
        scanf("%s",str);
        getnext(n);
        memset(dt,0,sizeof(dt));
        int sum=0;
        for(int i=1;i<=n;i++)
        {
            dt[i]=(dt[ne[i]]+1);
            sum=(sum+dt[i])%mod;
        }
        printf("%d\n",sum);
    }
    return 0;
}

掌握next[len]这个数的作用后,很多题都可以通过这个数找出规律,比如:POJ 2406、POJ 2752,可以拿来练手


猜你喜欢

转载自blog.csdn.net/wangjunchengno2/article/details/79105675