Power Strings(哈希)

Given two strings a and b we define ab to be their concatenation. For example, if a = “abc” and b = “def” then ab = “abcdef”. If we think of concatenation as multiplication, exponentiation by a non-negative integer is defined in the normal way: a^0 = “” (the empty string) and a^(n+1) = a*(a^n).
Input
Each test case is a line of input representing s, a string of printable characters. The length of s will be at least 1 and will not exceed 1 million characters. A line containing a period follows the last test case.
Output
For each s you should print the largest n such that s = a^n for some string a.
Sample Input
abcd
aaaa
ababab
.
Sample Output
1
4
3

题意

求最小子串出现次数

思路

哈希暴力查找每个循环串
~~*

代码

*~~

#include 
#include 
#include 
#include
using namespace std;
typedef unsigned long long ull;
ull base = 31;
ull po[1000005], hs[1000005];
char s1[1000005];

int main()
{
	po[0] = 1;
	for (int i = 1; i <= 1000005; i++)
		po[i] = po[i - 1] * base;
	while (scanf("%s", s1))
	{
		if (strcmp(s1, ".") == 0)
			break;
		int len = strlen(s1);
		ull n = 0;
		hs[len] = 0;
		for (int i = len - 1; i >= 0; i--)
		{
			hs[i] = hs[i + 1] * base + s1[i] - 'a' + 1;
		}
		for (int k = 1; k <= len; k++)
		{
			if (len % k != 0)
				continue;
			ull temp = hs[0] - hs[k] * po[k];
			int j = 0;
			for (j = k; j < len; j = j + k)
			{
				if (temp != hs[j] - hs[j + k] * po[k])break;
				else temp = hs[j] - hs[j + k] * po[k];

			}
			if (j == len)
			{
				n = len / k;
				break;
			}
		}
		cout << n << endl;
	}
	return 0;
}

你可能感兴趣的:(哈希字符串)