C语言记忆化搜索___Count the string(Hdu 3336)

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
 

题意:对于一个字符串,有固定的前缀子串,比如:"abab"的前缀子串有:“a”"ab""aba""abab";然后每个子串跟字符串匹配,求所有子串匹配成功次数.


分析:
可以采用记忆化搜索,用数组b来记录与前一个前缀串匹配的所有字串的最后一个字符。
第一次时记录下b,以后每次只要用a[b[j]+1]与最后一个字符去匹配

#include<stdio.h>
int b[200001];
char a[200001];
int main()
{
	int t,n,k,i,sum,ru,j;
	char pos;
	while(scanf("%d",&t)!=EOF)
	{
		while(t--)
		{
			scanf("%d",&n);
			scanf("%s",a);
			sum=0;
			k=0;
			pos=a[0];
			for(i=0;i<n;i++)
			{
				if(a[i]==pos)
				{
					sum++;
					b[k++]=i;
				}
			}
			sum=sum%10007;
			for(i=1;i<n;i++)
			{
				ru=k;
				k=0;
				pos=a[i];
				for(j=0;j<ru;j++)
				{
					if(a[b[j]+1]==pos)
					{
						sum++;
						b[k++]=b[j]+1;
					}
				}
				sum=sum%10007;
			}
			printf("%d\n",sum);
		}
	}
	return 0;
}




你可能感兴趣的:(C语言记忆化搜索___Count the string(Hdu 3336))