abcd aaaa ababab .
1 4 3
一开始理解错题意了,结果当然是wa,然后实在受不了就百度了一下,发现大家都在用一个什么定理,我还没找到那个定理是啥,不知道是不是真的是某个定理,也没有人解释一下,不过很好理解,假设S的长度为len,则S存在循环子串,当且仅当,len可以被len - next[len]整除,最短循环子串为S[len - next[len]],对这就是那个定理,其实很好理解的
这道题判断有几个循环的部分,除了循环没有冗余的元素,要求判断整个字符串有几个循环节,假设字符串为 a b c a b c的话对应的next数组应为-1 0 0 0 1 2,而next[6] = 3,如果是a b c a b c a b c的话对应的next数组应该是-1 0 0 0 1 2 3 4 5 而next[9] = 6,其实我想表达的就是如果这是一个循环字符串,那么next[len] = 总长度 - 减去单个循环节的长度,所以单个循环节的长度为 len - next[len],这样总的循环节个数为len /(len - next[len])
然而如果是aabbaa这种的应该怎么判断呢,其对应的next数组应该是-1 0 1 0 0 1然后next[6] = 2,此时判断时6%4 != 0,然而我怎么知道模数一定无法被整除呢,万一不是4是2呢,反正可以确定2是正确的情况,怎么证明出这个定理来还要好好想想啊
其实就是很简单,所以这道题告诉我说学好英语读懂题很重要(看备注说不定能看出来做这道题时心塞的心路历程)
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<vector>
#include<set>
#include<map>
#include<queue>
#include<cmath>
using namespace std;
char a[1000010];
int ne[1000010];
void findnext()
{
int i = 0, j = -1;
ne[0] = -1;
int len = strlen(a);
while(i < len)
{
if(j == -1 || a[i] == a[j])
ne[++i] = ++j;
else j = ne[j];
}
}
int main()
{
while(scanf("%s",a))
{
int len = strlen(a);
if(a[0] == '.')break;
findnext();
// int maxy = -2;
// for(int i = 0; i < len; i ++)
// if(ne[i] > maxy)
// maxy = ne[i];
if(len%(len - ne[len ]))
// if(ne[len] == 0)
printf("1\n");
else printf("%d\n",len/(len - ne[len ]));
}
return 0;
}