HDU-3366-Count the string(KMP,DP)
Count the string
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 14368 Accepted Submission(s): 6572
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
分析
- 如果枚举每一个前缀字串,然后KMP匹配的话,会超时,所以我们要利用KMP的特性来巧妙计算。
- KMP中的next数组表示的是最长公共前后缀字串长度,基于这一个特点。每次遍历到 i ,对于 next[i] 来讲,又重复出现了前缀长度为next[i] 的字串,基于这一特点,我们由前向后推出每一个 i 处的所有前缀重复数,所谓DP。
dp[i] = (dp[nxt[i]]+1)%mod;
即状态转移方程。也就是说,长度为 i 的前缀串中又多了一份长度为nxt[i]的前缀字串的个数,再加上自身,就是更新得到的数量。
const int mod = 10007;
const int MAX = 200005;
int dp[MAX];
int n;
int nxt[MAX];
char a[MAX];
void getnxt()
{
nxt[0] = -1;
int j = 0,k=-1;
while(j<n)
{
if(k==-1||a[j]==a[k])
nxt[++j] = ++k;
else
k = nxt[k];
}
}
int main()
{
int t;cin>>t;
while(t--)
{
cin>>n;
cin>>a;
getnxt();
long long ans = 0;
for(int i=1;i<=n;i++)
dp[i] = (dp[nxt[i]]+1)%mod;
for(int i=1;i<=n;i++)
ans = (ans+dp[i])%mod;
cout<<ans<<endl;
}
return 0;
}