HDU3336 next數組性質

K - Count the string

 
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
6

注意next數組的性質    內在有聯繫
開一個res數組   維護ans表示res數組和   res初始化爲0 1 1 1 ……(隱式初始化)

#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#include<algorithm>
#include<map>
#include<string>

using namespace std;

const int maxlen = 1000100;

int n;
int m;
int arrnext[maxlen+1];
int res[maxlen + 1];

char mai[maxlen];
char sub[maxlen];

void getnext()
{
	int i = 0;
	int j = -1;
	arrnext[0] = -1;
	int len = strlen(sub);
	while (i <= len)
	{
		if (j == -1 || sub[i] == sub[j])
		{
			j++;
			i++;
			arrnext[i] = j;
			//if (i-arrnext[i] != i&&i%(i-arrnext[i]) == 0)
			//{
			//	printf("%d %d\n", i, i / (i - arrnext[i]));
			//}
		}
		else
			j = arrnext[j];
	}
	//printf("%d\n",len%(len - arrnext[len])==0?len/(len - arrnext[len]):1);
}

void kmp()
{
	getnext();
	int ans = 0;
	int i = 0;
	int j = 0;
	int lenmai = strlen(mai);
	int lensub = strlen(sub);

	while (i < lenmai)
	{
		while (i < lenmai&&j < lensub)
		{
			if (j == -1 || mai[i] == sub[j])
			{
				i++;
				j++;
			}
			else
				j = arrnext[j];
		}

		if (j == lensub)
		{
			j = 0;
			ans++;
		}
	}//while

	printf("%d\n", ans);
}


int t;

int main()
{
	scanf("%d", &t);
	int key = 0;
	while (t--)
	{
		int x;
		scanf("%d", &x);

		//if (x == 0)
		//	break;
		key++;
		//scanf("%s",mai);
		scanf("%s", sub);
		//if (sub[0] == '.')
			//break;

		//printf("Test case #%d\n", key);
		//kmp();
		getnext();
		//printf("\n");
		int lensub = strlen(sub);
		//int ans = lensub - arrnext[lensub];
		//printf("%d\n", lensub%ans == 0 ? (lensub == ans ? ans : 0) : ans - (lensub%ans));

		int ans = 0;
		res[0] = 0;
		for (int i = 1;i <= lensub;i++)
		{
			res[i] = 1 + res[arrnext[i]];
			res[i] %= 10007;
			ans += res[i];
			ans %= 10007;
		}
		printf("%d\n", ans);
	}

	return 0;
}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章