HDU3336 Count the string(KMP,next的性质)

来源:互联网 发布:淘宝网店爆款打造 pdf 编辑:程序博客网 时间:2024/06/06 20:10

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

14abab

Sample Output

6

思路

给了一个字符串,让你输出这个字符串的前缀出现了几次,根据next的性质,我们知道,当next有值的时候,就证明肯定有一个匹配,所以我们统计出next数组里面>0的个数就是有多少个匹配,再加上与自身的匹配n就是答案

代码

#include <cstdio>#include <cstring>#include <string>#include <set>#include <iostream>#include <stack>#include <queue>#include <vector>#include <algorithm>#define mem(a,b) memset(a,b,sizeof(a))#define inf 0x3f3f3f3f#define mod 10007#define debug() puts("what the fuck!!!")#define N 200000+20#define ll long longusing namespace std;int nxt[N];string str[4500];void get_next(string s){    int len=s.length();    int j=0,k=-1;    nxt[0]=-1;    while(j<len)        if(k==-1||s[j]==s[k])            nxt[++j]=++k;        else            k=nxt[k];}int main(){    int t,n;    string s;    cin>>t;    while(t--)    {        cin>>n>>s;        ll ans=0;        get_next(s);        for(int i=1; i<=n; i++)            if(nxt[i])                ans++;        ans+=n;        ans%=mod;        cout<<ans<<endl;    }    return 0;}
原创粉丝点击