POJ-2406 Power Strings

Description

Given two strings a and b we define a*b to be their concatenation. For example, if a = "abc" and b = "def" then a*b = "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).

hash 先算出前缀 然后找一个长度 使得总字符串长度可以整除该长度 然后枚举 通过预先处理字符串前缀和然后判断

#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
char a[1001000];
int len,k=131;
long long now,mod=1000000007,hash[1001000];
long long cal(int x,long long y)
{
	long long re=1;
	while(x)
	{
		if(x&1) re=(re*y)%mod;
		x>>=1;y=(y*y)%mod;
	}
	return re;
} 
bool check(int x)
{
	long long cc=cal(x,(long long)k);
	for(int i=(x<<1);i<=len;i+=x)
		if((hash[i]-(hash[i-x]*cc)%mod+mod)%mod!=hash[x]) 
			return false;
	return true;
}
int main()
{
	while(1)
	{
		scanf("%s",a+1);
		len=strlen(a+1);
		if(len==1 && a[1]=='.') return 0;
		for(int i=1;i<=len;i++)
			hash[i]=(hash[i-1]*k+a[i])%mod;
		for(int i=1;i<=len;i++)
		{
			if(len%i==0 && check(i))
			{
				printf("%d\n",len/i);
				break;
			}
		}
	}
}

 

发表评论

邮箱地址不会被公开。 必填项已用*标注