1. 程式人生 > >poj 2406 Power Strings (字尾陣列)

poj 2406 Power Strings (字尾陣列)

Power Strings
Time Limit: 3000MS Memory Limit: 65536K
Total Submissions: 45998 Accepted: 19230

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).

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

Hint

This problem has huge input, use scanf instead of cin to avoid time limit exceed.

Source


題目大意:給出一個長度為L的字串,已知字串由某個字串S迴圈R次得到,求R得最大值。

標解是kmp

這題字尾陣列會TLE,我只是用來練習字尾陣列而已。

還是說一下字尾陣列的做法:列舉字串S的長度K,先判斷是否可以整除,如果可以整除,再判斷suffix(1)與suffix(k+1)的最長公共字首是否等於n-k。因為這道題suffix(1)是固定的,所以可以不用rmq,直接預處理出height陣列中的每個數到height[rank[1]]的最小值即可。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define N 1000003
using namespace std;
int n,m,len,sa[N],rank[N],height[N],xx[N],yy[N],*x,*y;
int mn[N],a[N],b[N],p;
char s[N];
int cmp(int i,int j,int l)
{
	return y[i]==y[j]&&(i+l>len?-1:y[i+l])==(j+l>len?-1:y[j+l]);
}
void get_SA()
{
	x=xx; y=yy; m=30;
	for (int i=1;i<=len;i++) b[x[i]=a[i]]++;
	for (int i=1;i<=m;i++) b[i]+=b[i-1];
	for (int i=len;i>=1;i--) sa[b[x[i]]--]=i;
	for (int k=1;k<=len;k<<=1){
		p=0;
		for (int i=len-k+1;i<=len;i++) y[++p]=i;
		for (int i=1;i<=len;i++)
		 if (sa[i]>k) y[++p]=sa[i]-k;
		for (int i=1;i<=m;i++) b[i]=0;
		for (int i=1;i<=len;i++) b[x[y[i]]]++;
		for (int i=1;i<=m;i++) b[i]+=b[i-1];
		for (int i=len;i>=1;i--) sa[b[x[y[i]]]--]=y[i];
		swap(x,y); p=2; x[sa[1]]=1;
		for (int i=2;i<=len;i++)
		 x[sa[i]]=cmp(sa[i-1],sa[i],k)?p-1:p++;
		if (p>len) break;
		m=p+1;
	}
	p=0;
	for (int i=1;i<=len;i++) rank[sa[i]]=i;
	for (int i=1;i<=len;i++){
		if (rank[i]==1) continue;
		int j=sa[rank[i]-1];
		while (i+p<=len&&j+p<=len&&s[i+p]==s[j+p]) p++;
		height[rank[i]]=p;
		p=max(0,p-1);
	}
}
int main()
{
	freopen("a.in","r",stdin);
	while (true) {
		scanf("%s",s+1);
		len=strlen(s+1);
		if (s[1]=='.') break;
		memset(b,0,sizeof(b));
		memset(sa,0,sizeof(sa));
		memset(rank,0,sizeof(rank));
		memset(height,0,sizeof(height));
		for (int i=1;i<=len;i++) a[i]=s[i]-'a'+1;
		get_SA();
		int pos=rank[1]; mn[pos]=1000000000;
		for (int i=pos+1;i<=len;i++) mn[i]=min(mn[i-1],height[i]);
		for (int i=pos-1;i>=1;i--) mn[i]=min(mn[i+1],height[i+1]);
		int ans=len;
		for (int i=1;i<=len;i++){
			if (len%i) continue;
			if (mn[rank[i+1]]==len-i) {
				ans=i;
				break;
			}
		} 
		printf("%d\n",len/ans);
	}
}