HDU 3336——Count the string
阅读原文时间:2023年07月11日阅读:1

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.

InputThe 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.

OutputFor 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

题意:找出来给出的字符串里面所有前缀在字符串中出现的个数

解法一:

这道题仔细一想和POJ-2752 Seek the Name, Seek the Fame很相似,2752这一道题目是求前缀和后缀的所有相同的长度

比如:

ababab

前缀和后缀相同的长度有4、2

这一道题就是让我们求前缀的在这个串中个数,那我们可以像2752这一道题一样,先找出来整个串相同前后缀的所有类型,在把串的长度依次递减,在对他求出来前后缀所有类型,很nice!

代码:

1 #include
2 #include
3 #include
4 #include
5 using namespace std;
6 const int maxn=200005;
7 const int INF=0x3f3f3f3f;
8 const int mod=10007;
9 char str[maxn];
10 void get_next(int len,int *next)
11 {
12 next[0]=-1;
13 int k=-1;
14 for(int i=1;i-1 && str[k+1]!=str[i])
17 k=next[k];
18 if(str[k+1]==str[i]) k+=1;
19 next[i]=k;
20 }
21 }
22 int main()
23 {
24 int t;
25 scanf("%d",&t);
26 while(t--)
27 {
28 int len;
29 scanf("%d",&len);
30 scanf("%s",str);
31 int next[len];
32 get_next(len,next);
33 int ans=0;
34 for(int i=len;i>0;--i)
35 {
36 int k=next[i-1];
37 while(k>=0)
38 {
39 k=next[k];
40 ans++;
41 }
42 ans%=mod;
43 }
44 ans+=len;
45 printf("%d\n",ans%mod);
46 }
47 return 0;
48 }

解法二:

例如:

ababab

我们知道他的相同前后缀的长度为4、2

当为4的时候分别为(1-4)==(3-6)那么此时的(1-3)==(3-5)是不是也是一种前缀在字符串中重复了一次(注意:这里的数字代表字符串下标,从1开始)

同理(1-2)==(3-4)且(1-1)==(3-3)

那么可以说加上了4,即next[6]

此时我们再看相同前后缀为2的时候,这个时候这个2都已经包含在了4里面,所以我们要注意只有next[i]!=next[i-1]+1的时候才可以直接加上next[i]

还不要忘记了最后加上一个字符串长度,因为前缀本身还没有计算在内

代码:

1 #include
2 #include
3 #include
4 #include
5 using namespace std;
6 const int maxn=200005;
7 const int INF=0x3f3f3f3f;
8 const int mod=10007;
9 char str[maxn];
10 void get_next(int len,int *next)
11 {
12 next[0]=-1;
13 int k=-1;
14 for(int i=1;i-1 && str[k+1]!=str[i])
17 k=next[k];
18 if(str[k+1]==str[i]) k+=1;
19 next[i]=k;
20 }
21 }
22 int main()
23 {
24 int t;
25 scanf("%d",&t);
26 while(t--)
27 {
28 int len;
29 scanf("%d",&len);
30 scanf("%s",str);
31 int next[len];
32 get_next(len,next);
33 int ans=next[len-1]+len+1;
34 for(int i=0;i=0 && next[i+1]!=next[i]+1)
37 ans=ans+next[i]+1;
38 ans%=mod;
39 }
40 printf("%d\n",ans%mod);
41 }
42 return 0;
43 }