【题解】HDU-3336 Count the string

Count the string(HDU-3336)

题面

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.

输入

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.

输出

For each case, output only one number: the sum of the match times for all the prefixes of s mod 10007.

样例输入

1
2
3
1
4
abab

样例输出

1
6

提示

思路

求next数组,每个相等的前后缀都会对它的回溯+1贡献。

代码

查看代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
char t[mxn];
int nxt[mxn], ans[mxn];

void getnxt(char* t, int m)
{
int i = 0, j = -1; nxt[0] = -1;
while (i < m)
{
if (j == -1 || t[i] == t[j]) {
i++, j++;
// if (t[i] == t[j])
// nxt[i] = nxt[j]; // next数组优化
// else
nxt[i] = j;
} else
j = nxt[j];
}
}

int main()
{
int T; scanf("%d", &T);
while(T--)
{
int m, mod = 10007;
scanf("%d %s", &m, t);
getnxt(t, m);
memset(ans, 0 ,sizeof(ans));
int sum = 0;
for(int i=1; i<=m; i++){
ans[i] = ans[nxt[i]] + 1;
sum = (sum + ans[i]) % mod;
}
printf("%d\n", sum);
}
return 0;
}
_/_/_/_/_/ EOF _/_/_/_/_/