两种做法,
一种KMP的next数组
一种是后缀数组
先说KMP:
举个例子可以看出来,比如abcabcabcabc ,next[len]=9,所以len-next[len]肯定是len的约数,并且此时len-next[len]也肯定为最短循环节。
也可以这么想,如果可以整除,那么肯定存在最短循环节,因为如果能整除你那么肯定前缀跟后缀字符串存在重叠,并且可以分为n个一样的子字符串,自己可以在纸上画一画。
#include
#include
#include
#include
using namespace std;
int next[1000005];
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
string s;
while(cin>>s)
{
memset(next,0,sizeof(next));
if(s[0]=='.')
break;
//i表示后缀,j表示前缀。
int i=0,j=-1;
next[0]=-1;
while(iif(j==-1||s[i]==s[j])
{
i++;
j++;
if(s[i]!=s[j])
next[i]=j;
else
next[i]=next[j];
}
else
j=next[j];
}
int len=s.size();
if((len)%(len-next[len])==0)
printf("%d\n",(len)/(len-next[len]));
else
printf("1\n");
}
return 0;
}
后缀数组我的这种做法思想类似KMP思想。
当然论文中还有另外一种做法
#include
#include
#include
#define F(x) ((x) / 3 + ((x) % 3 == 1 ? 0 : tb))
#define G(x) ((x) < tb ? (x) * 3 + 1 : ((x) - tb) * 3 + 2)
using namespace std;
const int N = 1000005*3;
int wa[N], wb[N], ws[N], wv[N], sa[N];
int rnk[N], height[N], r[N];
int c0(int *r, int a, int b) {
return r[a] == r[b] && r[a + 1] == r[b + 1] && r[a + 2] == r[b + 2];
}
int c12(int k, int *r, int a, int b) {
if (k == 2)
return r[a] < r[b] || r[a] == r[b] && c12(1, r, a + 1, b + 1);
return r[a] < r[b] || r[a] == r[b] && wv[a + 1] < wv[b + 1];
}
void Rsort(int *r, int *a, int *b, int n, int m) {
for (int i = 0; i < n; i++) wv[i] = r[a[i]];
for (int i = 0; i < m; i++) ws[i] = 0;
for (int i = 0; i < n; i++) ws[wv[i]]++;
for (int i = 1; i < m; i++) ws[i] += ws[i - 1];
for (int i = n - 1; i >= 0; i--) b[--ws[wv[i]]] = a[i];
}
void dc3(int *r, int *sa, int n, int m) {
int i, j, *rn = r + n, *san = sa + n, ta = 0, tb = (n + 1) / 3, tbc = 0, p;
r[n] = r[n + 1] = 0;
for (i = 0; i < n; i++) if (i % 3 != 0) wa[tbc++] = i;
Rsort(r + 2, wa, wb, tbc, m);
Rsort(r + 1, wb, wa, tbc, m);
Rsort(r, wa, wb, tbc, m);
for (p = 1, rn[F(wb[0])] = 0, i = 1; i < tbc; i++)
rn[F(wb[i])] = c0(r, wb[i - 1], wb[i]) ? p - 1 : p++;
if (p < tbc) dc3(rn, san, tbc, p);
else for (i = 0; i < tbc; i++) san[rn[i]] = i;
for (i = 0; i < tbc; i++) if (san[i] < tb) wb[ta++] = san[i] * 3;
if (n % 3 == 1) wb[ta++] = n - 1;
Rsort(r, wb, wa, ta, m);
for (i = 0; i < tbc; i++) wv[wb[i] = G(san[i])] = i;
for (i = 0, j = 0, p = 0; i < ta && j < tbc; p++)
sa[p] = c12(wb[j] % 3, r, wa[i], wb[j]) ? wa[i++] : wb[j++];
for (; i < ta; p++) sa[p] = wa[i++];
for (; j < tbc; p++) sa[p] = wb[j++];
}
void calheight(int *r, int *sa, int n) {
int i, j, k = 0;
for (i = 1; i <= n; i++) rnk[sa[i]] = i;
for (i = 0; i < n; height[rnk[i++]] = k)
for (k ? k-- : 0, j = sa[rnk[i] - 1]; r[i + k] == r[j + k]; k++);
}
char str[N];
int main() {
while (scanf("%s", str) == 1 && str[0] != '.') {
int len = strlen(str);
for (int i = 0; i <= len; i++)
r[i] = str[i];
dc3(r, sa, len + 1, 128);
calheight(r, sa, len);
int aa = len - height[rnk[0]];
int ans = 1;
if(len % aa == 0) {
ans = len / aa;
}
printf("%d\n", ans);
}
return 0;
}